Laravel: When creating a record with relations, cannot insert foreign key into table

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.

$request->user()->tasks()->create([
    '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',
    ]);

    $request->user()->people()->create([
        '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.


ANSWERS:


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.



 MORE:


 ? Bind the record to html.dropdownlist using ajax call in mvc
 ? Reseting Dropdown menu Jquery
 ? Where should I put new ListItem for DropDownList
 ? assign ng-model to ng-repeat (for dropdown selection)
 ? most readable programming language to simulate 10,000 chutes and ladders game plays?
 ? most readable programming language to simulate 10,000 chutes and ladders game plays?
 ? most readable programming language to simulate 10,000 chutes and ladders game plays?
 ? Considerations about a simulation game
 ? Modeling and Simulation Programming Language
 ? Simulating sports matches in online game