在 Laravel 5.6 中获取当前类别详细信息

Get Current Category details in Laravel 5.6

我正在尝试获取当前类别的详细信息。 例如,如果路线是 example.com/articles/category-slug

在我的文章类别模型中

public function article(){
      return $this->hasMany(Article::class);
  }

在文章模型中

public function category(){
         return $this->belongsTo(ArticleCategory::class, 'category_id');
    }

路线

Route::group(['prefix' => 'articles'], function(){
      Route::get('/', 'Frontend\ArticleController@index')->name('articles.index');
      Route::get('/{articlecategory}', 'Frontend\ArticleController@category');
      Route::get('/{articlecategory}/{slug}', 'Frontend\ArticleController@show');
    });

文章控制器

public function category(Request $request, ArticleCategory $articlecategory)
 {
   $category = $articlecategory->id;
   $currentcategory = ArticleCategory::where('id', $category)->first();
   return $currentcategory;
 }

我创建了两个类别,1. 更新 2. 新闻

当我转到 url example.com/articles/updates 时收到错误消息 "Page Not Found"

当我仅在路由文件中更改 {{ articlecategory }} to {{ category }} 时。它显示一个没有当前类别详细信息的空白页面。如何解决?

注意:我之前在 Laravel 5.5 中使用了相同的代码并且效果很好。在 Laravel 5.6 中,我看到了这个错误。我已经在 chrome 上使用缓存杀手,并且还按照 google 上几个链接的建议清除了 laravel 中的缓存和视图。但是我仍然看到同样的错误

你的路线应该是:

Route::group(['prefix' => 'articles'], function(){
      Route::get('/', 'Frontend\ArticleController@index')->name('articles.index')->name('articles');
      Route::get('/{category}', 'Frontend\ArticleController@category')->name('category');
      Route::get('/{category}/{slug}', 'Frontend\ArticleController@show')->name('category_articals');
    });

现在您要将 category_slug 传递给您的控制器然后

example: example.com/articles/news

在你的控制器中:

public function category(Request $request,$category)
 {
   $category = ArticleCategory::where('slug',$category)->first();
   if($category){
      // category found , return category to page
      return view('category',compact('category'));
   }else{
      // category not found , return 404 page
      return view('error.404');
   }
 }

我找到了一个有效的方法。

我已将路由键值更改为 slug,它起作用了。我认为这是由我使用的 slugs 包完成的。将以下代码手动添加到模型后,它按预期工作。

public function getRouteKeyName()
      {
          return 'slug';
      }

如果您希望模型绑定在检索给定模型时使用 id 以外的数据库列 class,您可以覆盖 Eloquent 模型上的 ‍‍getRouteKeyName 方法:

例如:

class ArticleCategory extends Model
{
    public $table='article_category';

    public function article(){
        return $this->hasMany(Article::class);
    }

    public function getRouteKeyName()
    {
        return 'category_slug';
    }
}

和我的 article_category table :

| category_slug |   name  | id |
|:-------------:|:-------:|:--:|
|      cat1     | Updates |  1 |
|      cat2     |   News  |  2 |