find or fail laravel
snippet in php

laravel find or fail exception

user5529

use Illuminate\Database\Eloquent\ModelNotFoundException;

// Will return a ModelNotFoundException if no user with that id
try
{
    $user = User::findOrFail($id);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
    dd(get_class_methods($e)); // lists all available methods for exception object
    dd($e);
}

find or fail laravel

user504

$model = App\Models\Flight::findOrFail(1);

$model = App\Models\Flight::where('legs', '>', 100)->firstOrFail();

laravel eloquent get first

user3440

// return first row by id
$user = App\User::where('id',$id)->first();
// or return directly a field
$userId = App\User::where(...)->pluck('id');

laravel find query

user5220

// Retrieve a model by its primary key...
$flight = App\Models\Flight::find(1);

// Retrieve the first model matching the query constraints...
$flight = App\Models\Flight::where('active', 1)->first();

// Shorthand for retrieving the first model matching the query constraints...
$flight = App\Models\Flight::firstWhere('active', 1);

laravel eloquent fill

user1776

$flight->fill(['name' => 'Flight 22']);

laravel find query

user2664

php artisan make:model Flight --migration

php artisan make:model Flight -m