hello world hello world - 3 months ago 15
PHP Question

laravel validation 5.1 with authenticated user

Im trying to do some validation on my registration form in my

validator
method. I'm concatenating
$user->id
to my
name
&
email
array keys so users cant register with the same name & email address thats already taken.

my
AuthController
below

<?php

namespace App\Http\Controllers\Auth;

use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

class AuthController extends Controller
{

use AuthenticatesAndRegistersUsers, ThrottlesLogins;

public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}

protected function validator(array $data)
{

return Validator::make($data, [
'name' => 'required|regex:/^[a-zA-Z]+$/u|max:255|unique:users,name,'.$user->id,
'email' => 'required|email|max:255|unique:users'.$user->id,
'password' => 'required|confirmed|min:6',
]);
}

}


every time i hit submit i get a
Undefined variable: user
error message so i try to add
$user = Auth::user();
above my validator method like this

// retrieve authenticated user
$user = Auth::user();
protected function validator(array $data)
{

return Validator::make($data, [
'name' => 'required|regex:/^[a-zA-Z]+$/u|max:255|unique:users,name,'.$user->id,
'email' => 'required|email|max:255|unique:users'.$user->id,
'password' => 'required|confirmed|min:6',
]);
}


but i get a
syntax error, unexpected '$user'
error message. I'm not sure what I'm overlooking.

Answer

When you are creating new User at the time you do not have any $user object and certainly you will get get a Undefined variable: user error message.

Your validation will work only for updating User profile.

There is a syntax error in you code. Here is the correct one:

 return Validator::make($data, [
        'name' => 'required|regex:/^[a-zA-Z]+$/u|max:255|unique:users,name',
        'email' => 'required|email|max:255|unique:users,email',
        'password' => 'required|confirmed|min:6',
    ]);
Comments