Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


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,662 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,662 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.