Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add additional key-value pair to request() before calling Laravel's create() method

Tags:

php

laravel

In Laravel, I am trying to insert all of the form input and add a new column, but it's not working as intended.

Example

$B2 = new B2;
$B2::create([
    request()->all(),
    $B2->column9 = "aaaa",
]);

The inserted database only insert column9, the other column is NULL.

like image 660
Tegar D Pratama Avatar asked Dec 30 '25 13:12

Tegar D Pratama


2 Answers

Because create() accepts an array as the only parameter:

public static function create(array $attributes = [])

You can do this:

$data = request()->all();
$data['column9'] = 'aaaa';
B2::create($data);
like image 140
Alexey Mezenin Avatar answered Jan 01 '26 04:01

Alexey Mezenin


When ever you use request all you must first make sure that you have either fillable fields in your model or guarded = to an empty array so for example:

class B2 extends Model
{

protected $table = 'db_table';

protected $fillable = [
    'email',
    'name',
];
}

or you can use

protected $guarded = [];

// PLEASE BE CAREFUL WHEN USING GUARDED AS A POSE TO FILLABLE AS IT OPENS YOU TO SECURITY ISSUES AND SHOULD ONLY REALLY BE USED IN TEST ENVIRONMENTS UNLESS YOU REALLY KNOW WHAT YOU ARE DOING!

As for your create method you should make sure its an associative array like this:

$B2::create([
    $B2->column9 => "aaaa",
]);

Or you could do something like:

    $data = $request->except('_token');
    $B2::create($data);
like image 41
Birdy Avatar answered Jan 01 '26 04:01

Birdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!