如果数据库中不存在该值,如何在Laravel Controller中引发重定向?

时间:2018-10-24 20:02:40

标签: php laravel

我有一个下拉类别选择标签,用于存储会话并将会话名称与存储在数据库中的类别标签匹配。一切正常,但是如果数据库中不存在类别名称,则会出现此错误Trying to get property 'catslug' of non-object。我该如何在我的代码中解决此问题:

 public function catbusiness(Request $request, $slug)
    {
       //this grabs all category in select tag
       $cats =  Category::orderBy('categoryname','ASC')->get();

        //this is the slug for individual category in url
        $catbread = Category::where('catslug', $slug)->first();

        session()->put('categoryname', $catbread->catslug);

        ->with('catbread', $catbread)

    }

view.blade.php

<select name="record" style="margin-top:5%;">
                    @foreach($cats as $categoryselect)
                    <option value="{{ $categoryselect->catslug  }}"
                        @if(session('categoryname') == $categoryselect->catslug)
                            selected="selected"
                        @endif >
                        {{ $categoryselect->categoryname }}
                    </option>
                @endforeach
                </select>

1 个答案:

答案 0 :(得分:1)

您可以使用if($_POST['xltype'] == 'keysum') { 这样的方法检查类别是否存在:

exists()