samedi 30 mars 2019

Laravel API, making a POST using two models

I'm doing an Attendant - Event registration using Laravel. I have a pivot table to relate an Attendant with his events. To register a new Attendant-Event, I created a new api route.

Route::post('attendants/{attendants}/events/{event}', 'AttendantController@eventRegistration');

And my controller looks like this:

public function eventRegistration(Request $request, Attendant $attendant, Event $event) {
    $attendant->events()->syncWithoutDetaching([
        $event->id
    ]);
    return new AttendantResource($attendant);
}

But I every time I send the post request to this method I got the next error:

local.ERROR: Argument 3 passed to App\Http\Controllers\Api\V1\AttendantController::eventRegistration() must be an instance of App\Models\Event, string given {"userId":1,"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Argument 3 passed to App\\Http\\Controllers\\Api\\V1\\AttendantController::eventRegistration() must be an instance of App\\Models\\Event, string given at /Users/jacobotapia/Documents/Macaco/smart-event-core/app/Http/Controllers/Api/V1/AttendantController.php:71)

My javascript code is the following:

eventRegistration(attendant, event) {
    const route = `${this.route}/${attendant.id}/events/${event}`;
    return this.httpService.makePost(route, {})
        .then(res => {
            return Promise.resolve(res);
        })
        .catch(err => {
            return Promise.reject(err);
        });
}

And the makePost method is the next one:

makePost(route, body, isFormData = false) {
    const endpoint = this.getEnpoint(route);
    const headers = this.getHeaders(isFormData);
    return window.axios.post(endpoint, body, {headers: headers}).then(res => {
        return res.data.data;
    })
    .catch(err => {
        return Promise.reject(err.response.data);
    });
}

I don't know why I'm getting the error, I'm passing a valid event id to the post method.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire