Home  >  Q&A  >  body text

Cannot use an object of type Illuminate\Validation\Validator as an array

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粉930448030P粉930448030286 days ago413

reply all(1)I'll reply

  • P粉427877676

    P粉4278776762023-12-13 10:50:24

    $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

    reply
    0
  • Cancelreply