在 laravel 5.3 中建立链接的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39639707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Right way to build a link in laravel 5.3
提问by JahStation
Im trying to build a dynamic link with a view page (blade) with Laravel 5.3.
我正在尝试使用 Laravel 5.3 构建带有视图页面(刀片)的动态链接。
My approach is:
我的做法是:
<a href=" {{ URL::to('articles') }}/{{ $article->id}}/edit">Edit></a>
that will output the right url with my base url and some other slug: http://mydomain/articles/23/edit
Where "23" is my article's id.
这将输出带有我的基本 url 和其他一些 slug 的正确 url: http://mydomain/articles/23/edit
其中“23”是我的文章的 id。
This works but I wonder if there is a cleaner way to do that?
这有效,但我想知道是否有更清洁的方法来做到这一点?
many thanks
非常感谢
回答by PeterPan666
You can use named routesfor this
您可以为此使用命名路由
// Your route file
URL::get('articles/{articleId}/edit', 'ArticlesController@edit')->name('articles.edit');
//Your view
<a href="{{ URL::route('articles.edit', $article->id) }}">Edit</a>
Much more cleaner IMO
更清洁的 IMO
回答by Vikash
You can use named routes for cleaner in code
您可以在代码中使用命名路由进行清洁
In your app/Http/routes.php (In case of laravel 5, laravel 5.1, laravel 5.2) or app/routes/web.php (In case of laravel 5.3)
在您的 app/Http/routes.php(如果是 laravel 5、laravel 5.1、laravel 5.2)或 app/routes/web.php(如果是 laravel 5.3)
Define route
定义路线
Route::get('articles/{id}/edit',[
'as' =>'articles.edit',
'uses' =>'YourController@yourMethod'
]);
In Your view page (blade) use
在您的视图页面(刀片)中使用
<a href="{{ route('articles.edit',$article->id) }}">Edit</a>
One benefits of using named routes is if you change the url of route in future then you don't need to change the href in view (in your case)
使用命名路由的一个好处是,如果您将来更改路由的 url,则不需要更改视图中的 href(在您的情况下)
回答by Rax Shah
You can try with this
你可以试试这个
<a href="{{ url('/articles/edit',$article->id) }}"><i class="fa fa-fw fa-edit"></i></a>
and your route.phpfile
和你的route.php文件
Route::get('/articles/edit/{art_id}', 'ArticlesController@edit');
Route::get('/articles/edit/{art_id}', 'ArticlesController@edit');
回答by Sebastian
I recommend to work with named routes!
我建议使用命名路由!
Your routes/web.phpfile:
你的路由/web.php文件:
Route::get('articles/{articleId}/edit', 'YourController@action')->name('article.edit');
Your Blade-Template file:
你的刀片模板文件:
<a href=" {{ route('article.edit', ['articleId' => $article->id]) }}">Edit></a>