I'm having a problem when I'm trying to create a child model associated to his parent.
I have 2 models:
When I click a Institution and I go to show.blade.php where I have a form to create an Address for that Institution I can't get from the request the field "instituion_id" which relates child with parent.
This is shown in the request:
Request Data
From the form I'm calling the following route: action="/institution/{{ $institution->id }}/addresses"
This is the code in AddressController:
public function store(Request $request)
{
// dd($request->all());
Address::create($request->all());
return back();
}
When I test it, the DB is asking for the isntitution_id column:
SQLSTATE[HY000]: General error: 1364 Field 'institution_id' doesn't have a default value (SQL: insert into
addresses
(address_name
,address_number
,address_full_name
,address_city
,address_state
,address_postal_code
,address_country
,updated_at
,created_at
) values (a, a, a, a, a, a, a, 2017-12-14 14:06:47, 2017-12-14 14:06:47))
So, how to I pass from the form the field "institution_id" and how do I get it in the controller and assocuiated to the child record?
I read many posts but in all of them they are just create a child record with one field but I want to process the complere request with all Addres fields.
Regards
You can access the id from the parameters of the store
method like this :
In the routes file :
Route::post('/institution/{institution_id}/addresses', 'YourController@store')
In the controller :
public function store($institution_id, Request $request)
{
$request->request->add(['institution_id' => $institution_id]);
// dd($request->all());
Address::create($request->all());
return back();
}
Ps : Don't forget to add institution_id
to the fillable fields in the Address Model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With