Laravel: передача параметров в FormRequest & Custom Rule - PullRequest
0 голосов
/ 28 ноября 2018

Я пытаюсь передать $this->repo, который я инициировал в контроллере, чтобы он был доступен в пользовательском классе правил EmployeeWorkingHours, который я вызываю с помощью EmployeeRequest, чтобы я мог получить данные из базы данных для проверки.

Ниже приведен пример кода:

Контроллер:

<?php

namespace Modules\ShopManager\Http\Controllers;

use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Modules\ShopManager\Entities\Repository\Contract\ShopManagerRepository;
use Validator;
use Modules\ShopManager\Http\Requests\EmployeeRequest;

class EmployeesController extends Controller
{
    public function __construct(ShopManagerRepository $repo)
    {
        $this->repo = $repo;

        $this->middleware(function ($request, $next) {

            $this->repo->setManagerId(Auth::id()); //new $repo(Auth::id());
            $this->shopId = $this->repo->getShopId();

            if (!is_null($this->shopId)) {
                $this->storagePath = 'images/shopmanager/shop/' . $this->shopId . '/employees';
            } else {
                abort(404);
            }

            return $next($request);
        });
    }

    public function store(EmployeeRequest $request)
    {           

        $data = $request->all();
        ...
        ...
    }
}

EmployeeRequest:

<?php

namespace Modules\ShopManager\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Modules\ShopManager\Rules\EmployeeWorkingHours;

class EmployeeRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|email',
            'from_hour' => ['required','numeric', new EmployeeWorkingHours],
            'to_hour' => ['required','numeric', new EmployeeWorkingHours],
            'status' => 'required|numeric',
            'profile_image' => 'image',
        ];
    }

    public function messages()
    {
        return [
            'profile_image.image' => 'Uploaded file is not an image.',
        ];
    }
    public function attributes()
    {
        return [
            'first_name' => 'First Name',
            'last_name' => 'Last Name',
            'email' => 'Email'
        ];
    }
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
}

EmployeeWorkingHours: Rule

<?php

namespace Modules\ShopManager\Rules;

use Illuminate\Contracts\Validation\Rule;

class EmployeeWorkingHours implements Rule
{
    private static $from;
    private static $to;
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        switch ($attribute) {
            case 'from_hour':
                self::$from = $value;
                break;
            case 'to_hour':
                self::$to = $value;
                return $this->_validate();
                break;
        }        
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Please select valid Time Interval From hour & To hour.';
    }

    private function _validate(){
        //dd(self::$from, self::$to);
        return false;
    }
}

1 Ответ

0 голосов
/ 28 ноября 2018

РЕШЕНИЕ

Я только что понял, попробовав это.Поскольку я связываю свой класс репозитория с синглтоном, я могу разрешить то же самое в любом месте моего EmployeeWorkingHours класса правил

private function _validate(){

    // by adding this line 
    $repo = resolve(ShopManagerRepository::class);        

    dd($repo->getShopHoursList());        
    return false;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...