Laravel Things I Always Lookup
Below is a list of things I frequently need to look up in the Laravel documentation. I’ve created this quick cheat sheet for myself, which you may also find interesting or helpful.
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
firstOrCreate
syntax
// Retrieve flight by name or create it if it doesn't exist...
$flight = Flight::firstOrCreate([
'name' => 'London to Paris'
]);
// Retrieve flight by name or create it with the name, delayed, and arrival_time attributes...
$flight = Flight::firstOrCreate(
['name' => 'London to Paris'],
['delayed' => 1, 'arrival_time' => '11:30']
);
upsert
syntax
Flight::upsert([
['departure' => 'Oakland', 'destination' => 'San Diego', 'price' => 99],
['departure' => 'Chicago', 'destination' => 'New York', 'price' => 150]
], uniqueBy: ['departure', 'destination'], update: ['price']);
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_admin' => 'boolean',
];
}
use Illuminate\Database\Eloquent\Casts\Attribute;
/**
* Get the user's first name.
*/
protected function firstName(): Attribute
{
return Attribute::make(
get: fn (string $value) => ucfirst($value),
);
}
Pivot table structure (not explicitly in the docs, but I need it enough to list here)
Schema::create('role_user', function (Blueprint $table) {
$table->foreignId('role_id')->constrained();
$table->foreignId('user_id')->constrained();
$table->primary(['role_id', 'user_id']);
});