dousa2794 2017-10-17 09:38
浏览 84
已采纳

无法通过slug获取项目而不是laravel中的id

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?

  • 写回答

1条回答 默认 最新

  • douwen0647 2017-10-17 09:48
    关注

    This is happening because there is no Item in the DB with ID = $items_route->id, so this code will return null:

    Item::with('taggs')->find($items_route->id);
    

    So, you need to check results:

    if (is_null($item)) {
        // Do some stuff.
    } else {
        // Item is not found.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 hexo+github部署博客
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?