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

dmag's avatar
Level 6

Resolve model from request

Is it possible to resolve a model from a request?

For example, a request passed to a controller, contains post_id => 5 and instead retrieving the model in the controller like so Post::find($request->post_id), I'd like to make that model available from the request automatically?

0 likes
6 replies
LaryAI's avatar
Level 58

Yes, it is possible to resolve a model from the request. You can use the Laravel's Route Model Binding feature to achieve this.

First, you need to define a route parameter in your routes file, like this:

Route::get('posts/{post}', 'PostController@show');

Then, in your controller, you can type-hint the model in the method signature, like this:

public function show(Post $post)
{
    // $post is now resolved from the request
}

Laravel will automatically resolve the model from the request and inject it into the controller method.

You can read more about Route Model Binding in the Laravel documentation.

1 like
dmag's avatar
Level 6

@LaryAI ok, but in my case it's api controller and the request has a number of different models that I'd like to resolve, for example the request has post_id as well as user_id, I'd like to resolve both into their models.

webrobert's avatar

@dmag, lary doesn't reply. He gets one shot. 😆

You add multiple the same way

Route::get('user/{user}/posts/{post}', 'PostController@show');
public function show(User $user, Post $post)
1 like
dmag's avatar
Level 6

@webrobert but how can I apply it to my code?

Route::post('/example-endpoint', [ExampleController::class, 'store']);

class ExampleController extends Controller
{
    public function store(Request $request)
    {
        dd($request->all());
       /*
       [
           'post_id' => 5,
           'user_id' => 12,
           ....
       ]
       */
    }
}
gainline's avatar

@dmag you'd need to bind them using your route.

Route::post('/example-endpoint/{user}/{post}', [ExampleController::class, 'store']);

// the URL would then be /example-endpoint/12/5

class ExampleController extends Controller
{
    public function store(Request $request, User $user, Post $post)
    {
        /*
		$user->id = 12
		$post->id = 5
		*/
    }
}
1 like
kokoshneta's avatar
Level 27

@dmag Route model binding only works with tokens passed to the controller method as part of the route URL. The request is resolved by the service container, but you can’t bind a model on a route based on the resolved request – the request isn’t part of the route.

1 like

Please or to participate in this conversation.