3

So let's say I've got a custom request called CreateReviewRequest.

In this request, I've got this method:

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'name'      => 'required_if(auth->logged)',
        'comments'  => 'required|max:255',
        'stars'     => 'required|min:1|max:5',
    ];
}

As you can see in the name key, I want from the client to be required to fill the name field if he's not logged in.

So my question is, how can I exactly require my client to fill the name when he's a guest?

Eliya Cohen
  • 10,716
  • 13
  • 59
  • 116

3 Answers3

8

You can use check() method:

public function rules()
{
    return [
        'name'      => auth()->check() ? 'required' : '',
        'comments'  => 'required|max:255',
        'stars'     => 'required|min:1|max:5',
    ];
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
0

Can't you make a simple check?

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    if (auth()->check()) {
        return [
            'comments'  => 'required|max:255',
            'stars'     => 'required|min:1|max:5',
        ];
    }

    return [
        'name'      => 'required',
        'comments'  => 'required|max:255',
        'stars'     => 'required|min:1|max:5',
    ];
}
Hammerbot
  • 15,696
  • 9
  • 61
  • 103
  • Or attach an auth middleware route to the controller method. – DevK Jan 26 '17 at 10:33
  • Attaching an auth middleware would not allow a guest to access the route am I wrong? – Hammerbot Jan 26 '17 at 10:33
  • You're right. It wouldn't solve OPs issue. I misunderstood at first. – DevK Jan 26 '17 at 10:34
  • @El_Matella I can achieve that goal with fewer lines by declaring a `$rules` var. I was just hoping that there's a custom role validation for that. – Eliya Cohen Jan 26 '17 at 10:34
  • A more elegant solution wil be to make a variable storing the array, like: `$rules = []; if (auth()->check()) $rules['name'] = 'required'; return $rules;` – HTMHell Jan 26 '17 at 10:35
0

Member only:

$validator = Validator::make($request->all(), [

     'email' => auth()->check() ? '' : 'required|min:5|max:60|email',

]);

Guest only:

$validator = Validator::make($request->all(), [

     'user_id' => auth()->check() ? 'required|integer|min:1' : '',

]);

Both:

$validator = Validator::make($request->all(), [

     'message' => 'required|min:10|max:1000'

]);

Combined:

$validator = Validator::make($request->all(), [

     'email' => auth()->check() ? '' : 'required|min:5|max:60|email',
     'user_id' => auth()->check() ? 'required|integer|min:1' : '',
     'message' => 'required|min:10|max:1000'

]);
Darren Murphy
  • 1,076
  • 14
  • 12