aahhaa
aahhaa

Reputation: 2275

Laravel Validate Against Auth::user()->id;

I am trying to avoid the paradox of admin remove its own admin role and got this error

Undefined variable: request

Undefined variable: thisUser

the variable is defined outside of the validation function,

below is the entire validation code, is there a way to do this with built-in validation?

public function edit(Request $request)
{

$thisUser = Auth::user();

$validatedData = $request->validate([
        'id' => 'required',
        'name' => 'required|alpha_num',
        'email' => 'required|E-Mail',
        'is_admin' => [
            'required', 
            'boolean', 
            function($attribute, $value, $fail) {
                if($thisUser->id == $request->input('id')) {
                    return $fail('Can not remove admin privilege of yourself');
                }
            }
        ]
    ]);

    ... 
    }

Upvotes: 0

Views: 1155

Answers (1)

Mozammil
Mozammil

Reputation: 8750

The closure won't have access to the variables defined outside its scope.

$validatedData = $request->validate([
    'id' => 'required',
    'name' => 'required|alpha_num',
    'email' => 'required|E-Mail',
    'is_admin' => [
        'required', 
        'boolean', 
        function($attribute, $value, $fail) use($thisUser, $request) {
            if($thisUser->id == $request->input('id')) {
                return $fail('Can not remove admin privilege of yourself');
            }
        }
    ]
]);

This should work.

Upvotes: 3

Related Questions