Cannot use an object of type Illuminate\Validation\Validator as an array
P粉930448030
P粉930448030 2023-12-12 11:40:54
0
1
482

While testing a post request to api/register, I received the following error in postman.

"Error: Cannot use an object of type IlluminateValidationValidator as an array in file C:Usersazzamlaravel-appazzamnewapiappHttpControllersAuthController.php on line 25"

This is my AuthController code:

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesAuth;
use IlluminateSupportFacadesValidator;
use AppModelsUser;
use LaravelSanctumPersonalAccessToken;

class AuthController extends Controller
{
    public function register(Request $request) {

    //validation field
        $validUser=Validator::make($request->all(), [
            'name'=> 'required|string',
            'email'=> 'required|email',
            'password'=> 'required|string',
        ]);
        

    //create user
        $user= User::create([
            'name'=> $validUser['name'],
            'email'=> $validUser['email'],
            'password'=> bcrypt($validUser['password']),
        ]);

    //response
        return response([ 
            'user'=> $user,
            'token'=> $user->createToken('secret')->plainTextToken,
        ], 200);
    }

    public function logout(Request $request) {

    //user
        $user= User::find(PersonalAccessToken::findToken(explode(' ',$request->header('Authorization'))[1])->tokenable_id);

    //delete token
        $user->tokens()->delete();

    //reponse
        return response([
            'message'=> 'logout success',
        ], 200);
    }

    
}

Can anyone tell me where the error is and how to view the $validUser variable? Thanks.

P粉930448030
P粉930448030

reply all(1)
P粉427877676

$validUser=Validator::make is a validator instance.

To validate and get validated input you can do the following:

$validUser = $request->validate([
    'name'=> 'required|string',
    'email'=> 'required|email',
    'password'=> 'required|string',
]);

If you must use a manually created validator instance, you can do the following:

$validUser = Validator::make($request->all(), [
    'name'=> 'required|string',
    'email'=> 'required|email',
    'password'=> 'required|string',
])->safe()->all();

These should work in Laravel 8

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!