How to get url parameter in controller in laravel?

by edmond_brakus , in category: PHP CMS , 14 days ago

How to get url parameter in controller in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 13 days ago

@edmond_brakus 

In Laravel, you can access URL parameters in a controller using the Request facade. Here's how you can do it:

  1. Import the Request facade at the top of your controller file:
1
use IlluminateHttpRequest;


  1. In your controller method, you can access the URL parameters using the Request facade like this:
1
2
3
4
5
public function someMethod(Request $request) {
    $paramValue = $request->route('parameter_name');
    
    // Do something with the parameter value
}


In the above code, replace 'parameter_name' with the name of the parameter you are trying to access in the URL.

  1. Alternatively, if you are using route model binding, you can type-hint the parameter in your controller method like this:
1
2
3
public function show(User $user) {
    // Use the user object retrieved from the route model binding
}


In this case, Laravel will automatically inject the User object based on the URL parameter that matches the model's primary key.