Call member function null Laravel

Submitted by lwinmaungmaung on
call member function null

We have faced a lot of problems working with Eloquent ORM. ORM is the most simple way to work with the database with a clean and beautiful code. However, sometimes with complex problems, they will bring you the most difficult things over the world. On of this thing, Call member function null is one of the problems with the text, call a member function on null, especially with the relationships which make difficult to debug.

call member function null

Why you run the program and you found the following text, call a member function on null. What does it mean? Before I found out the problem, that is really the worst thing I've ever seen. But time flies by, I found out the solution and I have some knowledge that why that problem arises.

Why this error?

When Eloquent has relationships and you tried to access via the relation, you think you will get the related data as easy as a charm. However, we all forget about one thing. We are trying to access the relation which will be available or not. If they are available, you will get the data like a charm but if there is nothing exist?

This is example Scenario:

There is a user and another has the login table. If User A has been logged in, A login records will come but User B has not logged in. There will be two results. The user table has two records but the Login record has only one record which relates to A.

So, when accessing the Login records of A, there will be the login record about him/her but when you are trying for B, there is no data for B. As a result, the data will become null. 

We try to access as follows:

$a = User::find(a);

$b = User::find(b);

$histories = $a->histories; // valid record

$histories = $b->histories: // invalid record call to a member function on null

So, when this is happened, make sure to check your data is access on null. If you have to cover, you have to do this thing.

$histories= ($b->histories?? '-')

if your history has multiple things. we write as follows:


    foreach($b->histories as $histories){



I hope this will solve your problem like a charm.