laravelroutescrm

adding a mass action to Laravel Application


I am trying to add a mass action for selecting leads and then updating the sales person. I added this route:

Route::post('mass-update-salesperson', 'LeadController@massUpdateSalesperson')->name('admin.leads.mass_update_salesperson');

and in the LeadController I added this method:

public function massUpdateSalesperson()
{
    $data = request()->all();

    foreach ($data['rows'] as $leadId) {
        $lead = $this->leadRepository->find($leadId);

        $lead->update(['user_id' => $data['value']]);

        Event::dispatch('lead.update.before', $leadId);
    }

    return response()->json([
        'message' => trans('admin::app.response.update-success', ['name' => trans('admin::app.leads.title')])
    ]);
}

and in the LeadDataGrid I added this code :

public function prepareMassActions()
{
    $stages = [];

    foreach ($this->pipeline->stages->toArray() as $stage) {
        $stages[$stage['name']] = $stage['id'];
    }

    $this->addMassAction([
        'type'   => 'delete',
        'label'  => trans('ui::app.datagrid.delete'),
        'action' => route('admin.leads.mass_delete'),
        'method' => 'PUT',
    ]);

    $this->addMassAction([
        'type'    => 'update',
        'label'   => trans('admin::app.datagrid.update_stage'),
        'action'  => route('admin.leads.mass_update'),
        'method'  => 'PUT',
        'options' => $stages,
    ]);

       //newly added
     $this->addMassAction([
        'type'    => 'update',
        'label'   => trans('admin::app.datagrid.update_salesperson'),
        'action'  => route('admin.leads.mass_update_salesperson'),
        'method'  => 'POST',
        'options' => $this->getUserDropdownOptions(),
     ]);
}

it reads the function but it won't update, any ideas why?

it gives an error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (crm-database.leads, CONSTRAINT leads_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: update leads set user_id = {"value":7,"label":"sales person name","disabled":false,"selected":false,"image_url":null}, leads.updated_at = 2023-06-16 18:39:11 where id = 2492)

noting that this user exists in the database.


Solution

  • Can you pls dump and share the value of that $data variable. It is failing because you are assigning user_id, which is supposed to be an integer, with this value:

    {"value":7,"label":"sales person name","disabled":false,"selected":false,"image_url":null}
    

    My guess is, you got to do this:

    use Illuminate\Support\Arr;
    
    $lead->update(['user_id' => $data['value']['value']]);
    
    // Or
    $lead->update(['user_id' => Arr::get($data, 'value.value')]);