protected function validator(array $data)
{
$validation = Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed']
]);
if ($validation->fails())
{
return session()->flash('alert-danger', 'error');
}
}
protected function create(array $data)
{
$company = new Company();
$company->store_name = $data['company_name'];
$company->save();
}
Check the fail status inside the validator function and show the error message
request()->validate([
'email' => 'required'
],
[
'email.required' => 'You have to choose the email!',
]);
try this below code instead of the above validation
request()->validate([
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
];
now if you remove the code
if ($validation->fails())
{
return session()->flash('alert-danger', 'error');
}
the code will run without any error .
and if you do not enter any value in the input field
the the request->validate() will check all the request.
You need to actually return something in your if ($validation->fails()) check. Right now, you're setting a session Flash, but returning null (->flash() has no return value).
You have a couple solutions here, but it depends if this is a Form Submission or an AJAX Request:
protected function validator(array $data) {
return Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed']
]);
}
protected function create(array $data) {
$validator = $this->validator($data);
if ($validator->fails()) {
session()->flash('alert-danger', 'error');
// If this is an AJAX Request:
if (request()->ajax()) {
return response()->json(['errors' => $validator->errors()], 422);
}
// If this is a Form Submission:
return back()->withErrors($validator->errors());
}
$company = new Company();
$company->store_name = $data['company_name'];
$company->save();
}
Basically, modify your validator method to return the Validator::make() instance, check it in your create() method, and return appropriately based on if this is an AJAX Request or Form Submission.
Related
I am experiencing this error when trying to register a user. The registration goes through i suppose because the data is inserted into the database but then it throws up this error instead of redirecting to dashboard.
I am kind of new to this so I am not sure where the error is coming from. I already tried searching for solutions online but not coming across any.
Here is my registerController
protected $redirectTo = RouteServiceProvider::HOME;
protected function redirectTo()
{
$user = auth()->user();
if ($user->role == 'guest') {
return route('guest.profile');
} else if ( $user->role == 'superadmin' ) {
return route('superadmin.home');
}
}
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Finally seen my error. Was supposed to add an else block to the redirect method.
Added it and error went away.
protected function redirectTo()
{
$user = auth()->user();
if ($user->role == 'guest') {
return route('guest.profile');
} else if ( $user->role == 'superadmin' ) {
return route('superadmin.home');
} else {
return route('home');
}
}
Thanks all for the help
I'm a beginner with laravel.
<?php
namespace App\Http\Controllers\Auth;
use ..
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/popin/create_adresse';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255', 'unique:customer'],
'password' => ['required', 'string', 'min:8'],
]);
}
protected function create(array $data)
{
$this->validator($data);
return Customer::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
In my router I have in get
"Route::get('login', 'PopinController#Login');
Route::post('register', 'PopinController#PostRegister');"
When I put some valid data, it's working ! But if I put an email who is already store in database, it's returning this exeption The given data was invalid..
How to create a custom error message like "This email is already use by another user !".
I don't understand.
Thank's for your help.
To retrieve errors use this:
protected function validator(array $data)
{
$validator = Validator::make($data, [
'email' => ['required', 'string', 'email', 'max:255', 'unique:customer'],
'password' => ['required', 'string', 'min:8'],
]);
if ($validator->fails()) {
return $validator->errors();
} else {
return [];
}
}
protected function create(array $data)
{
$errors = $this->validator($data);
...
It will return the list or errors you need
Hello all this is my update controller for an user. I want to know how can I apply these laravel validation rules ONLY to updated fields. Currently when I update only the first name, mobile number also get validated. My name fields are alpha validated and phone number is validated via regex.
public function update(Request $request, User $setting)
{
request()->validate([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:2', 'max:255'],
'mobile'=>['required', 'string','regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
]);
$setting->update($request->all());
return Redirect::back()->with('success','User updated successfully');
}
I able to handle the email(unique) field, but not the others.
Considering the small chat we had in the comments, what you must do is to first get the model from the database and to diff the request with the model's attributes. Then you can keep the validation rules for the changed attributes only.
public function update(int $id, Request $request, User $userRepository)
{
$user = $userRepository->find($id);
$changedAttributes = array_diff($request->all(), $user->getAttributes());
$validationRules = array_intersect_key([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:2', 'max:255'],
'mobile' => ['required', 'string', 'regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.''],
], $changedAttributes);
$this->validate($request, $validationRules);
$user->update($changedAttributes);
return Redirect::back()->with('success','User updated successfully');
}
I'm a beginner in programming, so please excuse my misunderstanding of validation in Laravel.
I'm trying to create a website for gamers of a specific game, where users can register. When they submit the form, I have to verify whether their account exists or not. To do this I have an external api (api from the game) which I can use to verify their account.
I tried to solve it like this in my RegisterController:
protected function validator(array $data)
{
$validation = $this->isSummonerValid($data['summonername']);
if ($validation) {
return Validator::make($data, [
'summonername' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'region' => ['required', 'string'],
'rank' => ['required', 'string'],
'lane' => ['required', 'array'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
} else {
return view('auth.register');
}
}
Everything which isSummonerValid() does is, it uses the API and returns true if the user exists in the game and false if not.
protected function isSummonerValid($summonerName)
{
$client = new Client();
try {
$response = $client->request('GET',
'https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/' . $summonerName .
'?api_key=' . APIKEY);
} catch (ClientException $e) {
return false;
}
return true;
}
When the API call succeeds, everything works fine. User gets created and can login.
When the API call fails (user doesn't exist) I get this error:
Method Illuminate\View\View::validate does not exist.
Can someone explain how I can create a custom validator in Laravel which calls an external API?
The validator() method of the RegisterController must always return an instance of Illuminate\Contracts\Validation\Validator class but you're returning lluminate\View\View on else condition, try to change the validator to this:
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return tap(Validator::make($data, [
'summonername' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'region' => ['required', 'string'],
'rank' => ['required', 'string'],
'lane' => ['required', 'array'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]),
function ($validator) use ($data) {
$validator->after(function ($validator) use ($data) {
if (! $this->isSummonerValid($data['summonername'])) {
$validator->errors()->add('summonername', 'Something is wrong with this field!');
}
});
}
);
}
I am migrating an old php-html website to vuejs/laravel.
There are already thousands of users so I guess I can't change the password cypting. For now, only mysql password() method is used to crypt it, and then we check that password(password)==password(authpassword).
But is it possible to add this password() in my laravel authentification? I already removed Hash.
public function login(Request $request){
$user = User::where('email', $request->email)
->where('pwd', $request->password)
->first();
if($user) {
Auth::login($user);
return redirect()->back();
} else {
return redirect()->back()->withInput();
}
}
registration
protected function validator(array $data)
{
return Validator::make($data, [
'nom' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255'],
'pwd' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'email' => $data['email'],
'login' => $data['email'],
'pwd' => ($data['password']),
'type' => 'P'
]);
}
public function register(Request $request)
{
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
}
Thanks a lot!