Search code examples
phpajaxlaravellaravel-5laravel-5.3

How to use different form requests in one controller in Laravel 5.3


I'm new on Laravel and I'm trying to create two different Form Request in order to use them on the same controller.

One of them will validate my forms before create and edit the model. (AngendaFormRequest) And the other will validate my AJAX actions. (AgendaAJAXFormRequest)

When I try to delete an event using AJAX and calling AgendaAJAXFormRequest as a parameter, my request keep passing through AgendaFormRequest methods.

How do I stop this behavior?

Here are my app setup:

Routes:

Route::group(['prefix' => 'agenda'], function(){
    Route::get('/', 'ConcertController@show');

    Route::get('/create', 'ConcertController@showRegistrationForm');
    Route::post('/create', 'ConcertController@create');

    Route::get('/{id}', 'ConcertController@showRegistrationForm');
    Route::post('/{id}', 'ConcertController@edit');

    Route::delete('/delete', 'ConcertController@delete');

    Route::get('/publish/{id}', 'ConcertController@publish');

});

AgendaFormRequest

class AgendaFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'title' => 'required|max:255',
            'date' => 'required|date',
            'time' => 'required',
            'group' => 'required',
            'href' => 'url'
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'title.required' => 'O título é um campo obrigatório',
            'date.required' => 'A data é um campo obrigatório',
            'date.date' => 'Este formato de data não é aceito',
            'time.required' => 'O horário é um campo obrigatório',
            'time.date' => 'Este formato de horário não é aceito',
            'group.required' => 'O campo projeto é obrigatório',
            'href.url' => 'Este formato de url não é aceito (tente: http://www.seu-site.com)',
        ];
    }
}

AgendaAJAXFormRequest

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;


class AgendaAJAXFormRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'id' => 'required'
        ];
    }


    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'id.required' => 'O id é obrigatório nesse tipo de requisição.',
        ];
    }
}

Delete and edit methods on ConcertController:

public function edit($id, AgendaFormRequest $req){
    $data = $req->all();

    try{
        $concert = Concert::findOrFail($id);
    } catch(\Exception $e) {
        return redirect()->back()->with('err', 'Evento não encontado');
    }

    $validators = [
        'time'=> 'date',
    ];

    $this->validate($req, $validators);

    $concert->update($data);

    return redirect($this->home)->with('alert', 'Evento editado com sucesso!');
}

/**
 * Delete the event of id = $id
 * @param  int $id 
 * @return string
 */
public function delete(AgendaAJAXFormRequest $req){
    try{
        $concert = Concert::findOrFail($id);
    } catch(\Exception $e) {
        return 'Evento não encontado';
    }

    $concert->delete();

    return "Evento $id deletado com sucesso!";
}

Javascript Request (jQuery)

$.ajax({
        url: href, // /agenda/delete
        type: 'POST',
        data: {
            id: id, // event id
            _token: window.Laravel.csrfToken,
            _method: 'DELETE'
        },
    })

Solution

  • This are often causes mistakes. Here are advises.

    Put your Route::delete('/delete', 'ConcertController@delete'); route above

    Route::get('/{id}', 'ConcertController@showRegistrationForm');
    Route::post('/{id}', 'ConcertController@edit');
    

    if that doesn't work then try

    $.ajax({
            url: href, // /agenda/delete
            type: 'DELETE',
            data: {
                id: id, // event id
                _token: window.Laravel.csrfToken,
            },
        })