vendredi 29 septembre 2017

Pass an attribute and it's value to a rule in a request

So I have a basic form, let's say for example:

<form action="" method="POST" role="form">
    <legend>Form title</legend>

    <div class="form-group">
        <label for="">label</label>
        <input type="text" name="main" class="form-control" id="" placeholder="Input field">
    </div>

    <div class="form-group">
        <label for="">label</label>
        <input type="text" name="test" class="form-control" id="" placeholder="Input field">
    </div>  

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Now, inside my controller's method, I am using a request:

public function store(CreateTestRequest $request)
{

}

Now, inside my request file, I have a rule for let's say the test input:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'main'      => 'required',
        'test'      => [
            'required',
            'numeric',
            new \App\Rules\Account\MyCustomRule,
        ],
    ];
}

Inside myCustomRule, I am trying to access, both the main's attribute and value, and the test's attribute and value, I can acccess the test's one by default, but I am not sure how to pass the other input's name and value to my custom rule... Is this possible? If so, how can I achieve this?

<?php

namespace App\Rules\Account;

use Illuminate\Contracts\Validation\Rule;

class MyCustomRule implements Rule
{
    /**
     * 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)
    {
        dd($value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Sorry. ';
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire