prgrm prgrm - 4 years ago 91
PHP Question

Cannot retrieve data from database using first() method

I have this routing:

Route::get('/item/{item_id?}',['uses'=>'ItemController@get_item_view']);


I want to redirect to the first item if no item ID is given.

public function get_item_view($id = null)
{


if($id == null)
{
#This doesnt work
$selected_item = Item::where('item_id',Auth::user()->item_id)->first();
}
else
{
#This works
$selected_item = Item::where('id',$id)
->where('item_id',Auth::user()->item_id)
->first();
}
if($selected_item === null)
{
return redirect('/');
}


return view('auth.forms.item')->with('item',$selected_item);
}


If I introduce an ID (www.myproject.com/item/2), the page works perfectly, but if I don't, and try to get just the first of the list just to generate the page. I expect www.myproject.com/item to give me the first item.

This is the error I get:


Trying to get property of non-object (View:
/var/www/myproject/resources/views/auth/forms/item.blade.php)


and when I use
dd($selected_item)
on both cases I get the same type of object. I have no idea why one is working and the other one isn't.

Answer Source

if you don't provide item id then it'll be null,

$selected_item = Item::where('item_id',null)->first();

if you want to list first item just do

if($id == null)
        {
#This doesnt work
            $selected_item = Item::all()->first();
        }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download