Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jove's avatar
Level 7

Need a little help understanding the generated controllers with resource

Hello, so If I generate a controller when creating a model and making the controller a resource controller it fills all the functions out, now Etc If it's a user controller:

/**
 * Display the specified resource.
 *
 * @param  User $user
 * @return \Illuminate\Http\Response
 */
public function show($user)
{

}

In this case, what does $user return, the routes are resource routes. I'm used to getting a ID then checking if it exists, does this do stuff like that? I just did a dump on it and I see it contains the user stuff like a find(id) does.

0 likes
7 replies
jonpemby's avatar
jonpemby
Best Answer
Level 5

The $user variable will be dynamically bound to an App\User as long as the route URI contains a {user} variable.

So in your routes/web.php:

Route::get('/users/{user}', 'UsersController@show');`

Your show method:

public function show(User $user)
{
    return $user;
}

Will output JSON of the $user. The route's user key will be an ID of the user unless you change it, so it'll basically work the same way you are expecting, you just don't have to find the user yourself.

So basically:

GET /users/1

Will return the User with an ID of 1.

Hope this helps! Let me know if you need more details.

Note: You will get a 404 response if the user does not exist, by the way.

1 like
jonpemby's avatar

@JOVEICE - That's when you'll need to find the resource yourself. It'll only automatically do it for you if the variable matches the route 'key'.

For example:

public function show(Resource $resource)
{
    return $resource;
}

Route:

Route::get('/resources/{foo}', 'ResourceController@show');

Won't automatically find the resource for you because foo doesn't match the $resource variable name.

However:

Route::get('/resources/{resource}', 'ResourceController@show');

Would match. :)

1 like
Cronix's avatar

Just a FYI - if you add the -m flag and specify a model, like User, in addition to the -r flag, it will prepopulate those in the method declarations as well.

php artisan make:controller UserController -r -m=User

So instead of

public function show($user)

it will create

public function show(User $user)

for the relevant methods.

1 like

Please or to participate in this conversation.