3

I have this problem. I have a Group and Role models, with a Many-to-Many relationship setup.

Group model

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

Role Model

public function groups()
{
    return $this->belongsToMany('App\Group', 'group_roles');
}

GroupsController store method

public function store(Request $requests)
{
    $group = new Group;
    //$group->group_name = $requests->group_name;
    //$group->save();
    $group->create($requests->all());

    $group->roles()->sync($requests->input('roles'));


   Session::flash('success', $requests->group_name.' successfully added');
   return redirect('/settings/groups/groups');

}

The problem I have here is that when I call create method on the group model, it returns null, thus causing this $group->roles()->sync($requests->input('roles')); to fail. However, when I use the save method, it works flawlessly. Why doesn't the create work?

EDIT: if I use create it does insert the records into the database, but the problem is that it's not return insertLastId.

2 Answers 2

2

In Group Model

public function groups()
{
    protected $fillable = ['group_name'] //add all the fillable fields
    return $this->belongsToMany('App\Group', 'group_roles');
}  

When create() method is used, it mass assigns all the values, so protected $fillable = [] should be used in that particular Model. see https://laravel.com/docs/5.1/eloquent#mass-assignment

For Last Insert Id use db function instead because create() method doesn't return lastInsertId, it only returns true if data inserted successfully.

return DB::('table_name')->insertGetId([
    'group_name' => 'some name'
]);
Sign up to request clarification or add additional context in comments.

4 Comments

I have protected $fillable = ['group_name']; already, right at the beginning of the model. The inserting works, but the problem is that its not returning lastInsertId despite the records being created in the database. I'm sorry if i gave little info
I've updated the answer. do let me know if it works.
Thanks for your suggestion, I try not to use query builders as much as possible. I would rather just call save method in this case. if create only returns true, then why does this work laracasts.com/series/laravel-5-fundamentals/episodes/23 - skip to 1:00, he's using the create method.
why do you have protected $fillable inside that method?
1

I have figured it out. I changed this:

$group = new Group;
$group->create($requests->all());

To

$group = Group::create($requests->all())

Now create returns the last insert ID.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.