Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel HasMany create child record

I'm having a problem when I'm trying to create a child model associated to his parent.

I have 2 models:

  • Instituion (has many addresses)
  • Address (has 1 Institution)

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

enter image description here

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

like image 413
Belisario Peró Avatar asked Mar 08 '23 08:03

Belisario Peró


1 Answers

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.

like image 178
Maraboc Avatar answered Apr 28 '23 18:04

Maraboc