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
. 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
<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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.