Home > Back-end >  How to use model class to edit , destroy and get single value in laravel 8 resource controller?
How to use model class to edit , destroy and get single value in laravel 8 resource controller?

Time:09-16

I want to develop an API with Laravel 8 with resource controller. Previously we used id parameter to edit, delete and get single value from the database. But now, here is given model class as a parameter in show, edit, update and destroy method. How can I use this model class to perform crud operations without id parameter? I know I’m on a misconception and I want to get a clear idea.

public function show(Food $food)
{
    //
}

public function edit(Food $food)
{
    //
}


public function update(Request $request, Food $food)
{
    //
}


public function destroy(Food $food)
{
    //
}

CodePudding user response:

This is just a better way of retrieving your data.

Instead of writing:

public function show($id)
{
    echo $id; // 12
    $food = Food::find($id); // your food instance with id 12
    echo $food->id; //12
}

You write:

public function show(Food $food)
{
    $food; // your food instance with id 12
    echo $food->id; //12
}

Laravel will match the parameter name of your route with the argument name in your controller method declaration and will automatically gives you the correct Food instance.

Your routes should looks like this:

Route::get('foods/{food}', [FoodController::class, 'show'])->name('foods.show');
// for each verbs (index, show, update...)
// the "food" parameter will be internally mapped 
// to the $food argument inside your controller methods declaration 

// or even simpler:

Route::resource('foods', FoodController::class);
// which will declare all routes for this resource

This is called implicit model binding. The documentation on this topic can be find here: https://laravel.com/docs/8.x/routing#implicit-binding

  • Related