Laravel 4:将什么作为参数传递给Url类?

Dir*_*irk 20 laravel laravel-4

有人可以解释Laravel 4 UrlGenerator类的语法吗?我在文档中找不到它.

我有以下路线:

Route::resource('users', 'UsersController');
Run Code Online (Sandbox Code Playgroud)

我花了很长时间才弄清楚这个:

{{ Url::action('UsersController@show', ['users' => '123']) }}
Run Code Online (Sandbox Code Playgroud)

生成所需的html:

http://localhost/l4/public/users/123
Run Code Online (Sandbox Code Playgroud)

我查看了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)
Run Code Online (Sandbox Code Playgroud)

..但这并没有真正带给我更多.

我能通过$parameters什么?

我现在知道这['users' => '123']有效,但这背景是什么?还有其他传递数据的方法吗?

Jas*_*wis 20

实际上并不需要将参数的名称作为数组的键.如果没有提供名字,替换将从左到右发生,据我所知.

例如,您的资源控制器路由定义将如下所示:

/users/{users}
Run Code Online (Sandbox Code Playgroud)

因此,URL::action('UsersController@show', ['123'])生成的URL会生成URL localhost/project/public/users/123,就像它已经为您一样.

因此,您传入的是正确生成URL所需的参数.如果资源是嵌套的,那么定义可能看起来像这样.

/users/{users}/posts/{posts}
Run Code Online (Sandbox Code Playgroud)

要生成URL,您需要传递用户ID和帖子ID.

URL::action('UsersPostsController@show', ['123', '99']);
Run Code Online (Sandbox Code Playgroud)

URL看起来像 localhost/project/public/users/123/posts/99


小智 11

那么在使用资源时有更好的方法来生成URL.

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
Run Code Online (Sandbox Code Playgroud)

希望这能说明问题.有关此文档,请访问http://laravel.com/docs/controllers#resource-controllers