Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Laravel - Inserting related models

I've seen here that there is a more refined way of adding related models.

I've gone ahead and added 'list items' to the Laravel ODOT application, and everything is working pretty well so far. I want to try and swap out this section my current 'STORE' method...


$content = Input::get('content');
$item = new TodoItem();
$item->content = $content;
$item->todo_list_id = $list_id;


with the following...


$content = Input::get('content');
$item = new TodoItem(['content' => $content]); //error occurs here 
$list = TodoList::findOrFail($list_id);
$item = $list->listItems()->save($item); 


I've tried to copy the example they give in the Laravel documentation, swapping out comments for items and posts for lists where applicable.

I've narrowed down the error message to this line


$item = new TodoItem(['content' => $content]);


It simply returns

"Illuminate \ Database \ Eloquent \ MassAssignmentException"

and in larger letters


You can see my whole project on github. I'm working on the cascade_item_delete branch.

Kevin Lozandier, with your experience of laravel, can you tell me what I'm doing wrong or give me any pointers?

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Tom,

I did some light reading on the subject and it appears to be simple to fix, based on Laravel's docs when using relational models you need to specify what database fields can be used as an mass assignment.

So for instance in your TodoItem model add a protected property called $fillable and assign your content field to it, it should look like the below.


class TodoItem extends Eloquent {

    protected $fillable = ['content'];

    // ...

Hopefully that helps.

Literally glorious, thanks Chris Upjohn . I don't know how familiar you are with rails.. but would this be similar to setting strong parameters?

Being an absolute laravel legend, might you take a look at this? https://teamtreehouse.com/forum/laravel-having-trouble-adding-a-foreign-key-to-column

Chris Shaw
Chris Shaw
26,676 Points

Sadly I don't have any experience with Rails as it's a language which I've never been able to grasp my fingers around, as for your other question I'm currently reading it.