【问题标题】:laravel5 generate routes keylaravel5 生成路由键
【发布时间】:2016-03-26 05:18:14
【问题描述】:

我现在使用 laravel 5.2。 我的 routes.php 文件中有这些代码:

Route::(['dashboard'=>'DashboardArticelController',]);

并且 laravel 为我的应用生成了一些路由器:

GET /dashboard/my-articles App\Http\Controllers\DashboardArticleController@getMyArticles

这是我的控制器中的一个方法:

public function getMyArticles()
{
    //$articels = Auth::user()->articals()->latest('published_at')->get(); 
    //dd(Auth::user()->articals()->latest('published_at')->simplePaginate(3));
    $articels = Auth::user()->articals()->latest('published_at')->Paginate(5);      
    return view('dashboard.view.dashboardArticelEdit',compact('articels'));
}

我想知道laravel5是如何生成这个路由的,我找不到方法可以生成带有方法名的路由。

【问题讨论】:

    标签: php laravel-5.2


    【解决方案1】:

    默认情况下,Laravel 假设 Eloquent 模型应该使用其 id 列映射到 URL 段。但是,如果您希望它始终映射到 slug 怎么办?

    Eloquent 实现了 Illuminate\Contracts\Routing\UrlRoutable 契约,这意味着每个 Eloquent 对象都有一个 getRouteKeyName() 方法,该方法定义了应该使用哪一列从 URL 中查找它。默认情况下,它设置为 id,但您可以在任何 Eloquent 模型上覆盖它:

    class Test extends Model 
    {
       public function getRouteKeyName()
       {
          return 'slug';
       }
    }
    

    【讨论】:

    • thanks.but 我发现类 RouteServiceProvider 中有一个方法 'boot',当我添加这个语句时:$router->model('one','App\Articles');进入该方法。我将模型对象 App\Articles 获取到我的方法'public function getMyArticles($Articles)'。但是方法'Route::(['dashboard'=>'DashboardArticleController',]);'生成一些像这样的路线: GET /dashboard/my-articles/{one?}/{tow?}/... 我怎样才能将键 {one?} 更改为 {articles?} 。因为我想用 Route 生成一些其他路线::controllers([])。它们都使用 'path/{one?}/{two?}/...' 生成路由
    • 你需要绑定隐式路由模型参考这篇文章mattstauffer.co/blog/implicit-model-binding-in-laravel-5-2。你会得到更好的主意。
    猜你喜欢
    • 2017-07-07
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2016-03-07
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多