How to use model class to edit , destroy and get single value in laravel 8 resource controller?

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)
{
    //
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x