Facebook
Twitter
LinkedIn
Instagram
Whatsapp
Call Now
Quick Inquiry

Undefined method 'posts' inside controller - in laravel ?

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

5 0

Write a Comments


* Be the first to Make Comment

GoodFirms Badge
GoodFirms Badge

Fix Your Meeting With Our SEO Consultants in India To Grow Your Business Online