| |

Laravel Query Error: [Trying to get property ‘id’ of non-object ] When trying to filter the query.

checked class name and variable name or same – failed.

when directly called ->get() or ->paginate() it works. but when the condition apply something changed.

Get Users! see the following code. It works well.

$usrs = User::orderBy('id', 'desc')->paginate();

When I try to add some filters in the query I got this error: [ Trying to get property ‘id’ of non-object ]. see the code.

        $usrs = new User();
        if ($this->status != null || $this->status != '') {
            $usrs->where('status', $this->status);
        if ($this->search != null || $this->search != '') {
            $usrs->where('id','LIKE', '%'.$this->search.'%' )
                ->orWhere('name','LIKE', '%'.$this->search.'%' )
                ->orWhere('email','LIKE', '%'.$this->search.'%' )
                ->orWhere('mobile','LIKE', '%'.$this->search.'%' )
                ->orWhere('city','LIKE', '%'.$this->search.'%' );
        $usrs->orderBy('id', 'desc')->paginate(5);

Check the spelling in the code. Plural and Singular names in the foreach loop. Everything was fine but the error continues.

@foreach ($users as $user)
  {{ $user->id }}

I use livewire, so I also check the livewire property name and the render passed variable name is the same. No. It’s unique.

If they are the same, that also causes the error. see the following code.

//livewire property
public $status = '';
public function render()
  $status = 'something';
  return view('livewire.users', compact('status'));

Then I will check the return types and inside the data with dd() method. I found there are differences in that return. So, After the filtering query, we must get the data to another specific variable.

$users = $usrs->orderBy('id', 'desc')->paginate(5);

Now I use it in the loop! It works!

I am not an expert in coding, please if there are any suggestions comment on them. thanks.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *