简体   繁体   中英

Laravel named routes parameter not working correctly

I'm currently using Laravel 5.3 and i have a number of routes similar to.

Route::get('/news/create/{product}', 'NewsController@create')->name('news::create');

So in my blade template im using the route() function like so:

{{route('news::create','car')}}

But the url generated is

/news/create?car

not the required

/news/create/car

The same thing happens if i put it in an array:

{{route('news::create',['car'])}}

And if i give it a key like so:

{{route('news::create',['product'=>'car'])}}

I get:

/news/create?product=car

How do I get the correct url so it is passed to the 'create' function as a parameter?

Firstly, take a look at your route naming. I don't think there's anything specifically wrong with naming a route like 'news::create' apart from it being ugly and quite probably considered bad practice. I like to go with camel casing , which means I'd use a name like createNews . It's much easier when going back to work on old sections of code and will stop other programmers from stabbing you if/when they work on a project with you.

The reason we can name routes is so that the name stays static even if we change the route URI or controller endpoint. We can pass variables to it using route parameters.

Route::get('/news/create/{product}', array('as' => 'createNews', 'uses' => 'NewsController@create'));


route('createNews', ['product' => 'car']);

{{route('news::create',['product => 'car'])}} Should fix your problem. Laravel uses named routes and expects an array with the keys as names with values.

Read all about it here: https://laravel.com/docs/5.3/redirects#redirecting-named-routes

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