Advertisement

TrimwebsolutionsTrimwebsolutions

Problem and Solutions

Undefined method 'posts' inside controller - in laravel ?

By M.K. Verma · 2 May 2022

Undefined method 'posts' inside controller - in laravel ?

First your posts relationship is wrong, it must be hasMany NOT belongsTo

public function posts() {
    return $this->hasMany(User::class);
}

Then it should work.

You can also try to create the model in a different way:

$validated = request()->validate([
    'title' => 'required|min:8|max:255',
    'post_image' => 'file',
    'body' => 'required'
]);

// Here you should check if $validated has all required fields
// because some could fail, in that case aren't in the array

Post::create([
  'title' => $validated['title'],
  'user_id' => auth()->id, // or auth()->user->id
  'post_image' => $validated['post_image'],
  'body' => $validated['body'],
]);