在Laravel中使用FormRequests的通用ResourceController

时间:2017-06-20 20:10:51

标签: laravel

我试图实现一个可以响应基本索引/ show / store / update / destroy调用的通用资源控制器。

我希望能够将特定的FormRequest类传递给此控制器,该控制器验证存储和更新调用的输入。但是,我还没有能够最后一点工作。

提前感谢您的帮助!

<?php
namespace App\Http\Controllers;

class ResourceController extends Controller
{
    private $model; //Resource this controller configures.
    private $formRequest; //A FormRequest for validating resource input.
    private $requestParams; //The possible parameters for resource input.

    public function __construct(String $modelClass, String $formRequestClass, array $requestParams){
        $this->model = $modelClass;
        $this->formRequest = $formRequestClass;
        $this->requestParams = $requestParams;
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return $this->model::all();
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store()
    {
        return $this->model::create(request($this->requestParams));
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        return $this->findResource($id);
    }

    /**
     * Update the specified resource.
     */
    public function update($id)
    {
        $resource = $this->findResource($id);
        $resource->update(request($this->requestParams));
        return $resource;
    }


    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $this->findResource($id)->delete();
    }

    private function findResource($id){
        return $this->model::find($id);
    }
}

1 个答案:

答案 0 :(得分:0)

首先,在视图中的表单中添加它。它将生成一个隐藏的令牌输入

{{ csrf_field() }}

其次,这是商店方法的外观

public function store()
{
    $this->validate(request(), [
      'title' => 'required'
      'body' => 'required'
    ]);

   Model::create($request->all()->except('_token'));

   return redirect()->back();    
}

或者像这样

public function store(Request $request)
{
    $this->validate($request, [
      'title' => 'required'
      'body' => 'required'
    ]);

    Model::create($request->all()->except('_token'));

    return redirect()->back();
}

更新

相同
public function update(Request $request)
{
    $this->validate($request, [
      'title' => 'required'
      'body' => 'required'
    ]);

    Model::create($request->all()->except('_token'));


    return redirect()->back();
}

在视图中添加此内容

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif