Brian Minton
0
Q:

find or fail laravel

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);
}
0
// return first row by id
$user = App\User::where('id',$id)->first();
// or return directly a field
$userId = App\User::where(...)->pluck('id');
1
// 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);
0
php artisan make:model Flight --migration

php artisan make:model Flight -m
0
$model = App\Models\Flight::findOrFail(1);

$model = App\Models\Flight::where('legs', '>', 100)->firstOrFail();
0
foreach ($flights as $flight) {
    echo $flight->name;
}
0
$flight->fill(['name' => 'Flight 22']);
0

New to Communities?

Join the community