[英]How do i throw a redirect in Laravel Controller if the value doesn't exist in the database?
I have a dropdown category select tag that stores the session and matches the session name to the category slug that stored in the database. 我有一个下拉类别选择标记,用于存储会话并将会话名称与存储在数据库中的类别标记匹配。 Everything works well but if a category name that doesn't exist in the database i get this error Trying to get property 'catslug' of non-object
. 一切正常,但是如果数据库中不存在类别名称,则会出现此错误, Trying to get property 'catslug' of non-object
。 How do i fix this problem here my code: 如何在我的代码中解决此问题:
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 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>
You can check if a category exists by using the exists()
method like this: 您可以通过使用exists()
方法检查类别是否存在,如下所示:
if(!Category::where('catslug', $slug)->exists()) //Check if the category exists.
{
return redirect()->route('your_not_found_route'); //Make a redirect
}
$catbread = Category::where('catslug', $slug)->first(); //If category exists fetch its data
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.