Injection dependency in an update method from the router

Published 10 months ago by ncrousset

Hello.

When I try to modify a record, eloquent creates a new record instead of modifying the instantiated.

public function editEmergencyContact(EmergencyContactRequest $request, EmergencyContact $emergencyContact)
{

    $application = Applications::findOrFail($request->application_id);

    if($application->Profile->user_id != Auth::id())
        return response()->json(['error' => 'Is not authorized to modify the registry'], 422);

    try {
        $input = $request->all();
        $input['updated_by'] = Auth::id();
        $input['updated_at'] = Carbon::now();

        $emergencyContact->fill($input);
        $emergencyContact->save();

    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage() ], 400);
    }

    //if ($request->ajax()) return;


    dd($emergencyContact);

    return response()->json($emergencyContact, 201);


}
Best Answer (As Selected By ncrousset)
swalker

Humm... Is it injecting the EmergencyContact correctly? does it have anything in the attributes property when you dd?

public function editEmergencyContact(EmergencyContactRequest $request, EmergencyContact $emergencyContact)
{
    dd($emergencyContact);
    // ...
}

note that you must use the variable with the same name that you have in your route like:

Route::patch('emergencycontacts/update/{emergencyContact}','[email protected]');

if you are using a resource route you can check it with the command php artisan route:list

swalker

Hello, try using the model's update method like:

try {
    $input = $request->all();
    $input['updated_by'] = Auth::id();
    // $input['updated_at'] = Carbon::now(); // you dont need this, its automatic

    $emergencyContact->update($input); //it will update and save

} catch (\Exception $e) {
    return response()->json(['error' => $e->getMessage() ], 400);
}
ncrousset

Sorry swalker2, I clicked to solve but it does not modify me in the DB. the update method return TRUE but no modify in the DB.

swalker

Humm... Is it injecting the EmergencyContact correctly? does it have anything in the attributes property when you dd?

public function editEmergencyContact(EmergencyContactRequest $request, EmergencyContact $emergencyContact)
{
    dd($emergencyContact);
    // ...
}

note that you must use the variable with the same name that you have in your route like:

Route::patch('emergencycontacts/update/{emergencyContact}','[email protected]');

if you are using a resource route you can check it with the command php artisan route:list

ncrousset

Yes, I am using the different name on the route but I repair it and everything is fine, Gracias @swalker2

Please sign in or create an account to participate in this conversation.