Home > Enterprise >  Newly added data into Laravel Request is not included in database insert query
Newly added data into Laravel Request is not included in database insert query

Time:07-27

I am trying to create a new customer record that will belong to the user who created it.

So I will get the user id and add it inside the $request before running Customer::create($request->all()).

Here is the code:

public function store(StoreCustomerRequest $request)
{
    // Get current logged in user's id
    $userId = Auth::user()->id;

    // Add user_id into request
    $request["user_id"] = $userId;

    // Store the newly created customer record
    Customer::create(array_merge($request->all()));
}

But after running these code, i found that the user_id is not included inside the SQL insert query.

enter image description here

I tried to use dd to print out the content inside $request->all() variable and i found that the user_id is included.

enter image description here

Is anyone know what is the problem about the newly added user_id is not included inside the SQL insert command.

Thanks.

CodePudding user response:

This should work:

Alternatively you could look at a modelObserver, and add the user_id during in the creating method.

public function store(StoreCustomerRequest $request)
{
    // Store the newly created customer record
    $newCustomer = Customer::make($request->validated());
    $newCustomer->user_id = Auth::id();
    $newCustomer->save();
}

CodePudding user response:

Mass Assignment!

Include "user_id" to the Customer model's fillable array.

  • Related