Tom Morison
Tom Morison

Reputation: 592

Laravel - $fillable filled, still getting MassAssignmentException

I have a very peculiar problem. I am trying to create a new entry in my database via Tinker. Whenever I run App\User::find(1)->message()->create(['message' => 'Hello from Coleigh']); I get a MassASsignmentException. The weird thing is I put the variables name in my fillable property. I don't understand why I am getting this.

I have been Googling for answers, but as you can see from my code, I have added my message field to both fillable properties. I have absolutely no idea why laravel isn't recognizing the message field.

Here are my models

namespace App;

use Illuminate\Database\Eloquent\Model;

    class Message extends Model
    {
        protected $fillable = ['message'];
        public function user() {
            return $this->BelongsTo(User::class);
        }
    }

and

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'message'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function profile()
    {
        return $this->hasOne('App\Profile');
    }

    public function roles() {
        return $this->BelongsToMany('App\Role');
    }

    public function hasRole($name) {
        foreach($this->roles as $role) {
            if ($role->name == $name) {
                return true;

            }

        }

        return false;

    }

    public function deposits() {
        return $this->hasMnay('App\Deposits');
    }

    public function isBlocked()
    {
        if ($this->banned) {
            return true;
        } else {
            return false;
        }
    }

    public function message() {
        return $this->hasMany(Message::class);
    }


}

Upvotes: 0

Views: 1502

Answers (3)

Hirad Roshandel
Hirad Roshandel

Reputation: 2187

It seems your missing user_id in Message $fillable. https://laravel.com/docs/5.6/eloquent#mass-assignment

Upvotes: 0

Tai Le
Tai Le

Reputation: 493

In class messsage, you should add one more column in $fillable property.

protected $fillable = ['user_id', 'message'];

Upvotes: 1

user9715413
user9715413

Reputation:

use save

$user = App\User::find(1);

$comment = new App\Message(['message' => 'Hello from Coleigh']);

$user->message()->save($comment);

Otherwise with create, you'd need to set the relationships id.

Upvotes: 0

Related Questions