【问题标题】:How to use different form requests in one controller in Laravel 5.3如何在 Laravel 5.3 的一个控制器中使用不同的表单请求
【发布时间】:2017-02-11 14:55:55
【问题描述】:

我是 Laravel 的新手,我正在尝试创建两个不同的表单请求,以便在同一个控制器上使用它们。

其中一个会在创建和编辑模型之前验证我的表单。 (AgendaFormRequest) 另一个将验证我的 AJAX 操作。 (议程AJAXFormRequest)

当我尝试使用 AJAX 删除事件并将 AgendaAJAXFormRequest 作为参数调用时,我的请求继续通过 AgendaFormRequest 方法传递。

如何阻止这种行为?

这是我的应用设置:

路线:

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)',
        ];
    }
}

议程AJAXFormRequest

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.',
        ];
    }
}

在 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 请求 (jQuery)

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

【问题讨论】:

  • 你能展示你的ajax和html代码吗?
  • 我添加了 Javascript 请求并注释了在 chrome 调试器上检查的变量值
  • 尝试删除您的验证并检查它是否采用了正确的方法。喜欢: public function delete(Request $req){ return "test" }
  • 即使我尝试使用标准 Request 类,它也会在 AgendaFormRequest 验证时返回错误

标签: php ajax laravel laravel-5 laravel-5.3


【解决方案1】:

这通常会导致错误。以下是建议。

把你的Route::delete('/delete', 'ConcertController@delete'); 路由放在上面

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

如果不行就试试

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

【讨论】:

  • 非常感谢!更改路线顺序有效!你知道是什么原因造成的吗?
  • 这是因为您正在发送 post 请求。而 laravel 正试图通过这条路线 Route::post('/{id}', 'ConcertController@edit');其中 id = 删除。但是当你改变位置时,laravel 首先检查路由 Route::delete('/delete', 'ConcertController@delete');。对不起英语。如果你不明白,我可以解释得更清楚。
  • 我明白了!再次感谢您!
  • 不客气!)你能把它标记为正确答案吗?
猜你喜欢
  • 2023-02-18
  • 2020-06-12
  • 2023-03-18
  • 2021-12-28
  • 2020-01-27
  • 2017-03-15
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多