【问题标题】:Controller Method not called with custom Form Request Method未使用自定义表单请求方法调用控制器方法
【发布时间】:2019-08-27 08:46:54
【问题描述】:

对于表单验证,我通过php artisan make:request UpdatePlanRequest 做了一个Request class

但是,在 store 中使用 UpdatePlanRequest 类后,不再调用该方法。

UpdatePlanRequest

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class UpdatePlanRequest 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()
    {   //TODO: CHECK IF THE PROTOTYPE IDS ARE OWNED BY THE USER (https://stackoverflow.com/questions/42662579/validate-an-array-of-integers/42693970)
        return [
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'name' => 'required|string'
        ];
    }
}

控制器方法:

use App\Http\Requests\UpdatePlanRequest;

public function store(UpdatePlanRequest $request)
    {
        //
        dd('hello');
    }

如果函数头是store(Request $request),则显示hello,在该示例中不是。

根据docs,为了验证目的,稍后需要自定义请求类调用$request-&gt;validated();

【问题讨论】:

  • 您可以编辑您的问题并添加您的路线以及创建表单吗?
  • 向我们展示表单本身。
  • 这是命名的问题。我做了一些错误的重构,同一件事有不同的术语。

标签: laravel laravel-5 laravel-5.8


【解决方案1】:

你的 Request 类是抽象的有什么原因吗?运行php artisan make:request &lt;name&gt; 时创建的默认类没有将类定义为抽象类。这似乎对我有用,但在将其声明为抽象时不起作用。

【讨论】:

    【解决方案2】:

    $request-&gt;validated(); 用于检索经过验证的输入,因此只需调用 UpdatePlanRequest 即可验证请求

    【讨论】:

    • 甚至没有调用 store 方法。我被重定向到 /create 页面。
    • @LewisTudor 您因为验证而被重定向;这应该发生
    【解决方案3】:
        //Try This 
        use App\Http\Requests\UpdatePlanRequest;
    
        public function store(UpdatePlanRequest $request)
            {
               $validatedData = $request->validated();
               dd('$validatedData');
               $profile = new Profile([
                'user_id'              => $request->get('user_id'),
    
            ]);
            $profile->save();
            echo $request->session()->flash('alert-success', 'Profile details Succefully Added!');
            return redirect('create')->with('success', 'Data saved!');
    
            }
    
    Your route will be.
    
    Route::get('profile','ProfileController@store');
    Route::post('profile/create','ProfileController@store')->name('create');
    

    【讨论】:

    • 甚至没有调用 store 方法。我被重定向到 /create 页面。
    • 检查创建页面上的验证错误:laravel.com/docs/5.8/…
    • 谢谢!验证错误检查让我解决了它。
    【解决方案4】:

    这很好用! 调用该方法时,它会检查请求类 (UpdatePlanRequest)。如果出现错误,则不再进入方法,并且看不到 dd() 函数的输出。 如果检查规则后数据正确,则会显示 dd()。 您必须管理错误

    【讨论】:

      猜你喜欢
      • 2016-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      相关资源
      最近更新 更多