Laravel: When Creating A Record With Relations, Cannot Insert Foreign Key Into Table

- 1 answer

I am following this exercise of an "intermediate task list" from Laravel 5.2 documentations and have some difficulty understanding how this piece of code works.

    'name' => $request->name,

Question 1

Specifically, I am confused at the relation between the user() and tasks() methods. Why and how exactly can we make the user() and tasks() methods available from the $request object?

Question 2

I created a similar app and has Person and Country models. I want to pass the country_id input from a dropdown list, but I can't get the database updated, using the following code.

public function store(Request $request)
    $this->validate($request, [
        'name' => 'required|max:255',
        'country_id' => 'required|max:3',

        'name' => $request->name,
        'country_id' => $request->country_id,

    return redirect('/people');

Why is it that the country_id cannot be saved to the table? I tried changing the user() to country() but the error message says, "class Country" was not found. But why is the 'user()' in the tutorial available then? I am baffled.



The user() method of request is available if the user making the request is authenticated.

Since it uses User model it can also fetch the related model. For tasks() to work Task relationship must be defined in user model.

For country_id to be created(mass assigned) ensure its included in $fillable property of the People model

$fillable = ['country_id']

Please read Eloquent model relationship section in Laravel documentation.