如何制作没有重定向到页面404的子弹

时间:2019-12-16 01:25:45

标签: laravel

我尝试了一个不在数据中的段,并收到了类似这样的错误: 试图获取非对象的属性“ id”

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上调用成员函数video()”

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

1 个答案:

答案 0 :(得分:1)

将检查添加到您的类别。

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
    }

}