问题
Can somebody explain the syntax of the Laravel 4 UrlGenerator class? I can't find it in the documentation.
I have the following route:
Route::resource('users', 'UsersController');
It took me long time to figure out that this:
{{ Url::action('UsersController@show', ['users' => '123']) }}
generates the desired html:
http://localhost/l4/public/users/123
I looked in UrlGenerator.php
/**
* Get the URL to a controller action.
*
* @param string $action
* @param mixed $parameters
* @param bool $absolute
* @return string
*/
public function action($action, $parameters = array(), $absolute = true)
..but that doesn't really bring me further.
What can I pass as $parameters
?
I now know that ['users' => '123']
works, but what's the background of this? And are there other ways of passing data?
回答1:
You aren't actually required to give the name of the parameter as the key of the array. The replacements will happen from left to right if no names are provided, as far as I can remember.
As an example, your resource controllers route definition will look something like this:
/users/{users}
So, a URL generated like URL::action('UsersController@show', ['123'])
will generate the URL localhost/project/public/users/123
, much like it has already for you.
So what you're passing in are the parameters required for the URL to be generated correctly. If the resource was nested, a definition might look something like this.
/users/{users}/posts/{posts}
To generate a URL you'd need to pass both the user ID and the post ID.
URL::action('UsersPostsController@show', ['123', '99']);
The URL would look something like localhost/project/public/users/123/posts/99
回答2:
Well there is a better way of generating URLs when working with resources.
URL::route('users.index') // Show all users links to UserController@index
URL::route('users.show',$user->id) // Show user with id links to UserController@show($id)
URL::route('users.create') // Show Userform links to UserController@create
URL::route('users.store') // Links to UserController@store
URL::route('users.edit',$user->id) // Show Editform links to UserController@edit($id)
URL::route('users.update',$user->id) // Update the User with id links to UserController@update($id)
URL::route('users.destroy',$user->id) // Deletes a user with the id links to UserController@destroy
Hope that clears things up. Some Documentation on this can be found here http://laravel.com/docs/controllers#resource-controllers
回答3:
For those using PHP 5.3, this should be:
URL::action('UsersController@show', array('123') )
来源:https://stackoverflow.com/questions/16141845/laravel-4-what-to-pass-as-parameters-to-the-url-class