简体   繁体   中英

how to get url parameter in controller in laravel?

my view blade.....

  tableHtml += "<td><a href= '{{url('/add')}}/" + data.hits[i].recipe.label + "'> add to favotite</a></td>";

when i click add to fav....i get this in url

http://localhost/lily/public/add/Chilli%20Green%20Salad

web.php

Route::get('/add', 'HomeController@add');

how can i get the url pass name in controller.....

public function add(Request $request)
{
 
$request->get("") ////////////how can i get the string i passed on url 

}

You need to add the parameter to the route. So, it should look like this:

Route::get('add/{slug}', 'HomeController@add');

And the add method:

public function add(Request $request, $slug)

Then value of the $slug variable will be Chilli Green Salad

https://laravel.com/docs/5.5/routing#required-parameters

You can do it like,

Route

Route::get('add/{data}', 'HomeController@add');

Controller

public function add(Request $request){
    // Access data variable like $request->data
}

I hope you will understand.

In your router.php :

Route::get('/add/{recipe}', 'HomeController@add'); // if recipe is required
Route::get('/add/{recipe?}', 'HomeController@add'); // if recipe is optional

In your `controller:

public function add(Request $request, $recipe) {
  // play with $recipe
}

Hope this will help!

Alter your url,add a get variabile

tableHtml += "<td><a href= '{{url('/add')}}/?slug=" + data.hits[i].recipe.label + "'> add to favotite</a></td>";

in your controller you use

public function add(Request $request)
{

echo $request->slug;

}
  1. If you have your parameter attached to the URL after the question mark like

http://www.siteurl.com/someRoute?key=value

Your route for this controller will look something like this

public function controllerMethod(Request $request) {
$key = $request->key
echo $key;
}
  1. If you have your parameter attached to the URL without question mark like

http://www.siteurl.com/someRoute/value

Your route for this controller will look something like this

Route::get('someRoute/{key}', $controller . 'controllerMethod');

You can get the value of this parameter in your controller function by passing the same name of variable in your controller method as you used in the route.

public function controllerMethod(Request $request, $key) {
echo $key;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM