Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

boxeur91's avatar

Trying to get property of non-object

hi I'm a newbie,

I would like to display all Students, where Student is Active.

I build a local Scope in my Model:


    public function scopeStudents()
    {
        return $this->where('is_student', true);
    }

my Controller looks like so:

class CourseMembersController extends Controller
{
    public function index(Course $course)
    {
        //dd($course);
        $users = User::students()->get()->toArray();
        return view('courses.members.index', compact('course', 'users'));
    }

}

I don't understand the Error "Trying to get property of non-object".

Can someone explain me?

0 likes
10 replies
patrykszady's avatar

How is is_student stored in the database? What are the values for yes and no/ active and inactive?

patrykszady's avatar

Haha I missed the ,true. Forget the scope for now, try

$students = User::where('is_student', true)->get();

Dd($students);

This should return a collection of all Users that are students

Cronix's avatar

Try using 1 instead of true in your scope. The error message is because it's returning null instead of an object (no results found) and you're then trying to run toArray() on null.

boxeur91's avatar

@patrykszady

The Scope is working.

$users = User::students()->get();
dd($users);

this return me also a Collection, but I do a foreach iteration in the View.

And that make the Error.

My view:

<select class="form-control" name="user_id" id="user_id">
                @foreach ($users as $user)
                        <option value=""> {{$users->name}} </option>
                @endforeach
</select>
patrykszady's avatar
Level 5

Try @jbloomstrom s suggestion. I think that's a very clean way to write this scope. Also, with and without the scope take out ->toArray. Have ->get(); be the last of that statement.

Is there a particular reason why you're toarray'ing? ....sorry on my phone so no annotations or tests here.

1 like
Cronix's avatar
@foreach ($users as $user)
    <option value=""> {{$users->name}} </option>
@endforeach

should be $user->name within the loop...not $users

1 like

Please or to participate in this conversation.