首页 > 解决方案 > 如何制作没有重定向到页面 404 laravel 的 slug

问题描述

我尝试了一个不在我的数据中的 slug,并在

videodetail.php

public function detail($slug)
{
    $video = Video::where('slug', $slug)->first();

    $blogKey = 'blog_' . $video->id;

    if(!Session::has($blogKey)) {
        $video->increment('view_count');
        Session::put($blogKey, 1);
    }

    $randomvideo = Video::whereHas('categories', function ($q) use ($video) {
        return $q->whereIn('name', $video->categories->pluck('name')); 
    })
    ->where('id', '!=', $video->id)
    ->approved()
    ->published()
    ->take(8)->get();
    return view('video.detail', compact('video', 'randomvideo'));
}

我在类别中收到此错误“在 null 上调用成员函数视频()”

public function videoByCategory($slug)
{
    $category = Category::where('slug', $slug)->first();
    $videos = $category->videos()->approved()->published()->paginate(21);
    return view('category.index', compact('category', 'videos'));
}

标签: laravel

解决方案


将检查添加到您的类别。

public function videoByCategory($slug)
{
    $category = Category::where('slug', $slug)->first();
    if ($category) {
      $videos = $category->videos()->approved()->published()->paginate(21);
      return view('category.index', compact('category', 'videos'));
    } else {
     // whatever you want to do
    }

}

推荐阅读