Home > Enterprise >  Laravel show with relationships
Laravel show with relationships

Time:09-27

How do you use the show function relationships? i know this works:

public show ($id) {   
    Model::with('relationship')->find($id);
}  

but with the new format

public show(Model $model) {

}

how do you include the relationship?

i've tried

$model->with('relationship')->get(); 

but it changes the value from an object to an array, what would be the proper way to do this?

CodePudding user response:

Lets lazy eager load that:

public show(Model $model) {
    $model->load('relationship');
}

CodePudding user response:

That's not a "new format". That's in fact Route model binding which is a convenient way to work as an API. https://laravel.com/docs/9.x/routing#route-model-binding

When you have a route such as

Route::get('/users/{user}', [UserController::class, 'show']);

Your controller will receive the model already fetched from database. If you need to use additional relationships you have 2 options (let's assume that user has a profile relationship):

Eager load on controller

public show(User $user) {
    $user->load('profile');
    return $user;
}

Or eager load in your RouteServiceProvider.php by using explicit binding. https://laravel.com/docs/9.x/routing#explicit-binding

/**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::bind('user', function ($value) {
        return User::with('profile')->findOrFail($value);
    });
}

Therefore you will have the user with it's profile in your controller

  • Related