skip to Main Content

I’m not sure why I couldn’t find it, but I need to get the value of the required parameter in the controller. For example if the route is /route/{param}, and if someone entered /route/123, I want to get 123:

public function some_method(Request $request)
{
    // get {param} value, 123
}

All I’ve seen is that it’s either used for route-model-binding or that it doesn’t use the Request (https://laravel.com/docs/10.x/routing#route-model-binding):

use AppHttpControllersUserController;
use AppModelsUser;
 
// Route definition...
Route::get('/users/{user}', [UserController::class, 'show']);
 
// Controller method definition...
public function show(User $user)
{
    return view('user.profile', ['user' => $user]);
}

*But perhaps I don’t even need Request $request because I can get it via the request() helper?

2

Answers


  1. You can have both Request parameter, value parameter or model binding, laravel is smart enough to recognize what’s type of data you expect (due to giving type to the parameter). So you can do:

    use AppHttpControllersYourController;
     
    // Route definition...
    Route::get('/route/{param}', [YourController::class, 'some_method']);
     
    // Controller method definition...
    public function some_method(Request $request, string $param)
    {
        ... // for /route/123 $param will have '123' value
    }
    

    if the id that you want to get is id of some model, then you can have both Request and model binding:

    use AppHttpControllersYourController;
    use AppModelsYourModel;
     
    // Route definition...
    Route::get('/route/{param}', [YourController::class, 'some_method']);
     
    // Controller method definition...
    public function some_method(Request $request, YourModel $param)
    {
        ... // for /route/123 you will get YourModel with id 123
    }
    
    Login or Signup to reply.
  2. If you want to get required parameter from route so here is a good example:

    web.php

    <?php
    
    use IlluminateSupportFacadesRoute;
    use AppHttpControllersSomeController;
    
    Route::get('/endpoint/{param}', [SomeController::class, 'someMethod']);
    

    SomeController.php

    <?php
    
    namespace AppHttpControllers;
    
    class SomeController extends Controller
    {
       public function someMethod($param)
       {
          // Now you can check the value
          // by using dd()
          dd($param);
       }
    }
    

    Note: Make sure your route parameter and function parameter must be with same name

    You can also access parameter value by using segment, here is another example:

    public function someMethod($param)
    {
       request()->segment(2);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search