Ben Ben - 4 months ago 27
PHP Question

Laravel mass assignment not saving fields

I have 2 tables within one function that I'd like to save data to. One is the

Users
table, and the second one is a
Clinic
table.

My user's table is currently working correctly, but I'm unsure if it's 'best practice':

$user = User::create([
'name' => Str::title($request->get('name')),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
])

->clinic()->create($request->only([
'name' => Str::title('clinic_name'),
'telephone',
'address_1',
'address_2',
'city',
'postcode'
]));


My problem occurs at the 'name' column of the
Clinic
table. It just doesn't save it, even though it's in the $fillable array in my
Clinic
column:

protected $fillable = ['user_id', 'name', 'telephone'', 'address_1',
'address_2', 'city', 'postcode'];


I have attempted to 'Chain' the methods together, as I want to save the 'user_id' within the
Clinic
table because they're related.

Many thanks for your help.

Answer

You're overriding the name key in your $request->only() call:

$user = User::create([
    'name' => Str::title($request->get('name')),
    'email' => $request->get('email'),
    'password' => bcrypt($request->get('password'))
])->clinic()->create($request->only([
    'name' => Str::title('clinic_name'), // This is overriding your 'name' field.
    'telephone',
    'address_1',
    'address_2',
    'city',
    'postcode'
]));

If you want to run Str::title() over the requests clinic_name, you'll need to assign the attributes manually like so:

$user = User::create([
    'name'     => Str::title($request->get('name')),
    'email'    => $request->get('email'),
    'password' => bcrypt($request->get('password'))
])->clinic()->create([
    'name'      => Str::title($request->get('clinic_name')),
    'telephone' => $request->get('telephone'),
    'address_1' => $request->get('address_1'),
    'address_2' => $request->get('address_2'),
    'city'      => $request->get('city'),
    'postcode'  => $request->get('postcode'),
]);

Note: Just as a tip, you can also just retrieve request input as a property like so:

->create([
    'name' => $request->name // Performs $request->get('name').
])
Comments