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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作