Home > database >  Undefined method 'posts' inside controller - Laravel
Undefined method 'posts' inside controller - Laravel

Time:05-01

I am getting error for undefined method which is defined inside my User model. My controller:

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

My Post model:

public function user() {
    return $this->belongsTo('App\Models\User');
}

My User model:

   public function posts() {
    return $this->hasMany('App\Models\Post');
}

CodePudding user response:

correct your relationship

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

CodePudding user response:

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

Laravel Validation Docs

  • Related