Laravel在浅层嵌套资源中请求验证 [英] Laravel request validation in shallow nested resource

查看:47
本文介绍了Laravel在浅层嵌套资源中请求验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个资源

  • 组织

OrganizationUsers

OrganizationUsers

鉴于我想同时在两种资源中创建,并且创建必须遵循特定的要求,所以我使用了request rules()和attribute().

Given that I want to create in both resources and that the creation must follow specific requirements, I'm using Request rules() and attributes().

例如,由于组织需要具有唯一的名称,因此我正在使用

For instance, since organizations need to have a unique name, I'm using

public function rules()
    {
        return [
            'name' => [
                'required', 'min:3', Rule::unique((new Organization)->getTable())->ignore($this->route()->organization->id ?? null)
            ],
            (...)
        ];
    }

,效果很好.调整相同流程以验证组织用户

and that works fine. Adapting the same process to validate organization users

class OrganizationUserRequest extends FormRequest
{
     
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'user_id' => [
                'required', 'exists:'.(new User)->getTable().',id', Rule::unique((new OrganizationUser)->getTable())->ignore($this->route()->user->id ?? null)
            ],
            (...)
        ];
    }

    /**
     * Get the validation attributes that apply to the request.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'user_id' => 'user',
            (...)
        ];
    }
}

然后我尝试添加的任何用户都会给我一个

then whatever user I try to add will get me a

用户已被带走.

无论使用哪个用户.

OrganizationUser模型是

The OrganizationUser model is the

class OrganizationUser extends Model
{
    protected $fillable = [
        'user_id', (...)
    ];

    /**
     * Get the user
     *
     * @return \App\User
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    (...)

}

此外,OrganizationUserController也是如此

Also, the OrganizationUserController is as

/**
 * Show the form for creating a new organization
 *
 * @return \Illuminate\View\View
 */
public function create($id, Organization $model1, User $model2)
{

    return view('organizations.users.create', [
        'id'=> $id,
        'organizations' => $model1::where('id',$id)->get(['id', 'name']),
        'portal_users' => $model2->all(),
        ]);
    
}

以及create.blade.php中的该字段

and that field in create.blade.php

<div class="form-group{{ $errors->has('user_id') ? ' has-danger' : '' }}">
    <label class="form-control-label" for="input-user_id">{{ __('User') }}</label>
    <select name="user_id" id="input-organization" class="form-control{{ $errors->has('user_id') ? ' is-invalid' : '' }}" placeholder="{{ __('User') }}" required>
        @foreach ($portal_users as $portal_user)
            <option value="{{ $portal_user->id }}" {{ $portal_user->id == old('user_id') ? 'selected' : '' }}>{{ $portal_user->name }}</option>
        @endforeach
    </select>
    @include('alerts.feedback', ['field' => 'user_id'])
</div>

推荐答案

为了解决该问题,我已经完成了后续步骤

In order to solve it, I've gone through the next steps

  1. 创建提供商

php artisan make:provider UniqueOrgUserServiceProvider

  1. 在该提供商中

<?php

namespace App\Providers;

use App\OrganizationUser;
use Illuminate\Support\ServiceProvider;

class UniqueOrgUserServiceProvider extends ServiceProvider
{    
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        \Validator::extend('uniqueorguser', 
                    function($attribute, $value, $parameters, $validator)
        {
            $value1 = (int)request()->get($parameters[0]);
            if (is_numeric($value) && is_numeric($value1))
            {
                return (!(OrganizationUser::where($attribute, $value)
                    ->where($parameters[0], $value1)
                    ->count() > 0));
            }
            return false;
        });
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

}

  1. config/app.php
  2. 中注册提供程序
  1. Register the provider in config/app.php

'providers' => [

        /*
         * Application Service Providers...
         */
        App\Providers\UniqueOrgUserServiceProvider::class,

    ],

  1. OrganizationUserRequest 更改为

class OrganizationUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => [
                'required', 'min:3'
            ],
            'is_admin' => [
                'required','boolean'
            ],
            'organization_id' => [
                'required', 'exists:'.(new Organization)->getTable().',id'
            ],
            'user_id' => [
                'required', 'uniqueorguser:organization_id', 'exists:'.(new User)->getTable().',id',
            ]
        ];
    }

    /**
     * Get the validation attributes that apply to the request.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'user_id' => 'user',
            'organization_id' => 'organization'
        ];
    }

    public function messages()
    {
        return [
            'user_id.uniqueorguser' => 'The user already exists in this organization!'
        ];
    }
}


此答案基于此.

这篇关于Laravel在浅层嵌套资源中请求验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆