Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I get this error when I insert a new post in the db "Call to a member function load() on null"

When I try to add a new post I get the error

Call to a member function load() on null

and this is my PostController:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public function index($id = NULL)
    $posts = Post::all();

    $user = User::find($id)->load(['posts']);     
    return view('post.index', compact('posts','user'));
}

TABLES:

countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string

How can I fix it?

>Solution :

If there is probability of $id is null or don’t exists I can advice at least use findOrFail instead of find

$user = User::findOrFail($id)->load(['posts']);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading