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

Time:08-09

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:

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?

CodePudding user response:

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']);
  • Related