I'm trying to make my URL's a bit user friendly but I'm unable.
I have added in my RouteServiceProvider
this
Route::bind('items_route', function ($value) {
return \App\Item::where('alias', $value)->firstOrFail();
});
This is my route.php
Route::get('item/{item}', 'ItemController@show')->name('item.show');
The button in my view
{!! HTML::linkRoute('item.show', 'View', array($item->alias)) !!}
And the controller
public function show( Item $items_route )
{
$reviews = Review::where('item_id', $items_route->id)->where('approved', 1)->get();
$item = Item::with('taggs')->find($items_route->id);
$additionAds = Item::with('taggs')->where('id', '!=', $items_route->id)->get();
if($item) {
$item->views = (int) $item->views +1;
$item->save();
}
$category = Category::find($item->category_id);
if($category->parent_id == 0) {
$ids = Category::select('id')->where('parent_id', $item->category_id)->where('parent_id','!=',0)->get();
$array = array();
foreach ($ids as $id) {
$array[] = (int) $id->id;
}
$items = Item::select('*')->whereIn('category_id',$array)->whereNotIn('id', [$item->id])->get();
} else {
$items = Item::select('*')->where('category_id' ,$item->category_id)->whereNotIn('id', [$item->id])->get();
}
$item_images = Item_Images::where('item_id',$items_route->id)->get();
$defaultCountry = DB::table('items')
->leftJoin('countries', 'items.country_id', '=', 'countries.id')
->where('items.id', $items_route->id)
->select('items.*', 'countries.*')
->first();
return view('item', compact('item','items','item_images','defaultCountry', 'additionAds', 'reviews'));
}
The error is
ErrorException in ItemController.php line 40: Trying to get property of non-object
Line 40 is where making query for Category $category = Category::find($item->category_id);
. The error appears because the $item
is null.
Can anyone tell whats going on here? Why I can't get the item and all attributes from the controller?