I'm using this code for User Sign Up in Laravel:
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'phone' => $validatedData['phone'],
'type' => $validatedData['type'],
'verified' => $validatedData['verified'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.
Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .
How can I achieve this ? Thank you.
You can get a User record from the database by phone. If the record exists, then do your logic
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
// get a user record by phone
$record = User::where('phone', $validatedData['phone'])->find();
if (!empty($record)) {
return response()->json([
'error' => 'this phone number has been used'
])
}
//.....
}
Related
ok, I'm trying to login the users after success registration into their panels. the database line built successfully. but alternately user login become successful but once not.
Here is the Request Controller Code:
$request->merge(['phone'=> '09123456789']);
$request->merge(['name' => 'User']);
$request->merge(['password' => 'pass123456789']);
$request->merge(['email' => 'user#email.com']);
$credentials = $request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required',
'email' => 'required',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $credentials['phone'],
'password' => Hash::make($credentials['password'])
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->route('panel');
}
The Model:
protected $fillable = [
'name',
'phone',
'email',
'password',
];
let me know if I didn't describe perfectly
First, I would stop using validation in the controller and use form request validation instead. It's been the standard since Laravel 5.
Try this simplified code using Auth::login() instead:
public function createUser(Request $request)
{
$request->validate([
'name' => 'required|string|max:64',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required|string|max:64',
'email' => 'required|email|max:64',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect()->route('panel');
}
I'm Importing a CSV file to a livewire component and trying to run some validation for each row of the file but I'm having problems doing this. It seems that my validation is doing nothing.
Here is how my Livewire component looks like:
namespace App\Http\Livewire\Modals;
use Validator;
use Livewire\Component;
use App\Http\Traits\Csv;
use App\Models\AccountUser;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
class ImportExtensions extends Component
{
use WithFileUploads;
public $clientID;
public $showModal = false;
public $upload;
public $columns;
public $fieldColumnMap = [
'first_name' => '',
'last_name' => '',
'email' => '',
'password' => '',
'extension' => '',
'user_type' => '',
];
protected $rules = [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.extension' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|max:255',
];
protected $validationAttributes = [
'fieldColumnMap.first_name' => 'First Name',
'fieldColumnMap.last_name' => 'Last Name',
'fieldColumnMap.email' => 'Email',
'fieldColumnMap.password' => 'Password',
'fieldColumnMap.extension' => 'Extension',
'fieldColumnMap.user_type' => 'User Type',
];
public function updatingUpload($value)
{
Validator::make(
['upload' => $value],
['upload' => 'required|mimes:txt,csv'],
)->validate();
}
public function updatedUpload()
{
$this->columns = Csv::from($this->upload)->columns();
$this->guessWhichColumnsMapToWhichFields();
}
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
//Validate the data of each Row to make to make sure you don't import duplicate records
$this->validateOnly(collect($eachRow), [
'fieldColumnMap.first_name' => 'required|max:255',
'fieldColumnMap.last_name' => 'required|max:255',
'fieldColumnMap.email' => 'required|max:255|email|unique:account_users, email',
'fieldColumnMap.extension' => 'required|numeric|unique:account_users, extension',
'fieldColumnMap.password' => 'required|max:255',
'fieldColumnMap.user_type' => 'required|in:user,admin',
]);
//If validation fails, it should skip the create extension part and run the next row
//If validation pass, then create the Extension
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
});
$this->reset();
$this->emit('refreshExtensions');
$this->notify('Successfully Imported '.$importCount.' Extensions');
}
Also, how can I make so that if the validation fails it goes to the next row instead of trying to create the extension.
Thanks.
I was able to create custom rules for just this. if one row fails validation, I just throw an error. So, basically either all rows pass or all fails.
Here is how it looks like now:
public function import()
{
// Validate that you are importing any data
$this->validate();
$importCount = 0;
Csv::from($this->upload)
->eachRow( function ($row) use (&$importCount){
$eachRow = $this->extractFieldsFromRow($row);
$validatedData = Validator::make([
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
],[
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:account_users',
'extension' => 'required|numeric|unique:account_users',
'password' => 'required|max:255',
'user_type' => 'required|in:user,admin',
],);
if($validatedData->fails()){
$this->notify(['error','Oops something went wrong!']);
}else{
AccountUser::create([
'user_id' => Auth::user()->id,
'account_id' => $this->clientID,
'first_name' => $eachRow['first_name'],
'last_name' => $eachRow['last_name'],
'email' => $eachRow['email'],
'password' => $eachRow['password'],
'extension' => $eachRow['extension'],
'user_type' => $eachRow['user_type'],
]);
$importCount++;
}
});
$this->reset();
$this->emit('refreshExtensions');
if($importCount!=0) $this->notify(['success','Successfully Imported '.$importCount.' Extensions']);
}
I'm trying to update a user, as an admin.
I'm changing the username, but it says email must be unique.
How do I fix this.
public function update($id, PutUser $request)
{
if (auth()->id() == $id) {
return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.');
}
$user = User::find($id);
$user->update((array_merge($request->validated(), ['county' => request('county')])));
//Update model_has_roles model with assignees_roles
return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}
This is the request class
public function authorize()
{
return true;
}
public function rules()
{
$user_id = $this->input('id');
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
}
}
I keep getting a failed email validation. 'Email has already been taken'. Any idea
You are missing a comma after the email label in your validation:
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email,'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:
use Illuminate\Validation\Rule;
return [
'email' => [
'required',
Rule::unique('users', 'email')->except($user_id),
]
];
https://medium.com/#tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40
I used laravel 5.2 to build my app but suddenly validation doesn't work out on registration`new users
Route::post('/register','userController#store');
my function on validation part for storing users details
public function store(Request $request)
{
$this->validate($request,[
'fname' => 'required|max:50',
'lname' => 'required|max:50',
'email' => 'required|email|unique:users',
'phone' => 'required|unique:users',
'provider' => 'required',
'company' => 'required',
'password' => 'required|min:8',
'IDtype' => 'required',
'IDnumber' => 'required',
'region' => 'required|max:32',
'signature' => 'required'
]);
}
Things were working well but now return
"fname":["validation.required"],"lname":["validation.required"],"email":["validation.required"],"IDtype":["validation.required"],"IDnumber":["validation.required"]} returned as response
`
You shoud use $request->all() instead of $request
public function store(Request $request)
{
$this->validate($request->all(),[
........
]);
}
In Laravel 5.5 you can call the validate method on request and it's recommended
$request->validate($rules);
I don't know how to get the query string array to validate in Laravel Validation.
here is my code
public function addUserByAdmin(Request $request){
$this->validate($request,[
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
$uesrAction = new UserAction($this->repository);
$user = $uesrAction->addUser($request->input('phone'),$request->input('password'),$request->input('name'),$request->input('fullname'),$request->input('position'));
if($user){
return response()->json(['success' => 'success','user'=>$user]);
}
return response()->json(['success' => 'fail']);
}
but validation doesn't work.Then I tried Validation::make() method and also didn't work.
My URL be like
http://localhost:8000/admin/users/add-user?phone=abcdefg&password=erer&name=ere&fullname=rere&position=343
If you are using laravel 5.5, change your code as follows:
public function addUserByAdmin(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
// ...
}
One of the features that was added in this update is that other way to use the validate() method:
More info:
https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic
https://laravel.com/docs/5.5/releases