Laravel Resume
Laravel Resume
Laravel Resume
Project commands
// New project
$ laravel new projectName
// Launch server/project
$ php artisan serve
// commands list
$ php artisan list
// command help
$ php artisan help migrate
// Laravel console
$ php artisan tinker
// Route list
$ php artisan route:list
Commons commands
// Database migration
$ php artisan migrate
// Data seed
$ php artisan db:seed
// Create a controller
$ php artisan make:controller ProductsController
// up()
Schema::table('users', function (Blueprint $table) {
$table->text('comment');
});
// down()
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('comment');
});
Models
// Model mass assignment list exclude attributes
protected $guarded = []; // empty == All
// in Tag model...
public function posts()
{
return $this->belongsToMany(Post::class);
}
// in Post model...
public function tags()
{
return $this->belongsToMany(Tag::class);
}
Factory
// ex: database/factories/ProductFactory.php
public function definition() {
return [
'name' => $this->faker->text(20),
'price' => $this->faker->numberBetween(10, 10000),
];
}
// all fakers options : https://github.com/fzaninotto/Faker
Seed
// ex: database/seeders/DatabaseSeeder.php
public function run() {
Product::factory(10)->create();
}
Running Seeders
$ php artisan db:seed
// or with migration
$ php artisan migrate --seed
Eloquent ORM
// New
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
// Update
$flight = Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();
// Create
$user = User::create(['first_name' => 'Taylor','last_name' => 'Otwell']);
// Update All:
Flight::where('active', 1)->update(['delayed' => 1]);
// Delete
$current_user = User::Find(1)
$current_user.delete();
// Delete by id:
User::destroy(1);
// Delete all
$deletedRows = Flight::where('active', 0)->delete();
// Get All
$items = Item::all().
// Chain
$flights = App\Flight::where('active', 1)->orderBy('name', 'desc')->take(10)->get();
// Where
Todo::where('id', $id)->firstOrFail()
// Like
Todos::where('name', 'like', '%' . $my . '%')->get()
// Or where
Todos::where('name', 'mike')->orWhere('title', '=', 'Admin')->get();
// Count
$count = Flight::where('active', 1)->count();
// Sum
$sum = Flight::where('active', 1)->sum('price');
// Contain?
if ($project->$users->contains('mike'))
Routes
// Basic route closure
Route::get('/greeting', function () {
return 'Hello World';
});
// Route Redirect
Route::redirect('/clients', '/customers');
// Route Parameters
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
// Optional Parameter
Route::get('/user/{name?}', function ($name = 'John') {
return $name;
});
// Named Route
Route::get(
'/user/profile',
[UserProfileController::class, 'show']
)->name('profile');
// Resource
Route::resource('photos', PhotoController::class);
// Nested resource
Route::resource('photos.comments', PhotoCommentController::class);
// Partial resource
Route::resource('photos', PhotoController::class)->only([
'index', 'show'
]);
Route::resource('photos', PhotoController::class)->except([
'create', 'store', 'update', 'destroy'
]);
// Generating Redirects...
return redirect()->route('profile');
// Route fallback
Route::fallback(function () {
//
});
Cache
// Route Caching
php artisan route:cache
Controllers
// Set validation rules
protected $rules = [
'title' => 'required|unique:posts|max:255',
'name' => 'required|min:6',
'email' => 'required|email',
'publish_at' => 'nullable|date',
];
// Validate
$validatedData = $request->validate($rules)
// Show 404 error page
abort(404, 'Sorry, Post not found')
// app/resources/views/products/index.blade.php
return view('products.index', ['products', $products]);
}
return redirect(route('products.index'));
}
return redirect(route($product->path()));
}
Template
<!-- Route name -->
<a href="{{ route('routeName.show', $id) }}">
@method(‘PUT’)
@csrf
Helpers
// Display variable content and kill execution
dd($products)
// Set Session
$request->session()->put('key', 'value');
// Get session
$value = session('key');
If session: if ($request->session()->has('users'))
// Delete session
$request->session()->forget('key');
HTTP Client
// Use package
use Illuminate\Support\Facades\Http;
//Http get
$response = Http::get('www.thecat.com')
$data = $response->json()
// Http post
$res = Http::post('http://test.com', ['name' => 'Steve','role' => 'Admin']);
// Bearer
$res = Http::withToken('123456789')->post('http://the.com', ['name' => 'Steve']);
// Headers
$res = Http::withHeaders(['type'=>'json'])->post('http://the.com', ['name' => 'Steve']);
// Delete file
Storage::delete('file.jpg');
// Trigger download
Storage::disk('public')->download('export.csv');
Heroku deployment
// Install Heroku on local machine (macOs)
$ brew tap heroku/brew && brew install heroku
// Create Procile
$ touch Procfile
// Save in Profile
web: vendor/bin/heroku-php-apache2 public/
API Resource (Layer that sits between your models and the JSON
responses)
$ php artisan make:resource ProductResource
Authorization rules
You can create a token with pre-define auth rules
$user->createToken('dev token', ['product-list']);
// in controllers
if !auth()->user()->tokenCan('product-list') {
abort(403, "Unauthorized");
}