Before you mark this question as a duplicate of this question, first understand that this question is based on Laravel 8 while the former is on Laravel 5.4 which handle the auth differently.
I would like to add a named error bag on laravel validation during registration. I am using the default laravel auth
php artisan ui bootstrap --auth
Below is the class that handles registration.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
Registration is handled by register method in the above class. Laravel has hidden this method and imports it to the above class using the use RegistersUsers; declaration.
To add a named error bag as explained here, I need to access this hidden register method. How do I do it.
I know that one way of doing this is by writing my own register method, but is there an alternative?
I need to add a named error bag because my login and register forms are in the same page.
You should pass the validator to named error bag, so it can be achieved by overriding register method from RegisterUsers trait:
public function register(Request $request)
{
$validator = $this->validator($request->all());
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return redirect('register')->withErrors($validator, 'login');
}
Or you can validate it with an error name bag
public function register(Request $request)
{
$validator = $this->validator($request->all())->validateWithBag('login');
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return redirect('register');
}
Related
I'm using default auth in laravel and want to send array with some data from some table to register.blade.php. I've just tried this one (method from RegisterController):
public function checkgroup(){
$group=Group::all();
return view('auth.register', compact ('group'));
}
But it still return "undefined variable group". I've tried with another controllers and views-works good.
AnŠ² here is a part of register.blade.php
<select name="checkgroup">
#foreach($group as $groups)
<option value="{{$groups->id}}">{{$groups->name}}</option>
#endforeach
</select>
RegisterController
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data, Request $request)
{
$user=User::create([
/*dd($request->role),*/
'name' => $data['name'],
'patro' => $data['patro'],
'surname' => $data['surname'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->assignRole($request->input('role'));
}
public function checkgroup(){
$group=Group::all();
return view('auth.register', compact ('group'));
}
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all(), $request)));
$this->guard()->login($user);
if ($response = $this->registered($request, $user)) {
return $response;
}
return $request->wantsJson()
? new JsonResponse([], 201)
: redirect($this->redirectPath());
}}
Seems you are using laravel/ui package for auth related scaffolding. As per this the showRegistrationForm method handles the /register route to show the registration form.
You can check which Controller and method is responsible for handling the route by running php artisan route:list in the terminal.
The controller method to show the registration form is within the RegistersUsers trait.
You need to override that method to pass additional data to the register view.
Have this method in your RegisterController
public function showRegistrationForm()
{
$groups = Group::all();
return view('auth.register', compact('groups');
}
Then in your auth/register.blade.php include the snippet for the groups
<select name="checkgroup">
#foreach($groups as $group)
<option value="{{$group->id}}">{{$group->name}}</option>
#endforeach
</select>
I'm working with Laravel 8 to develop my project, and I have made a Resource Controller under the Admin directory, which goes like this:
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
public function update(Request $request, User $user)
{
$data = $request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email',
'max:255', Rule::unique('users')->ignore($user->id)],
]);
if (!is_null($request->password)) {
$request->validate([
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
$data['password'] = $request->password;
}
$user->update($data);
if ($request->has('verify')) {
$user->markEmailAsVerified();
}
return redirect(route('admin.users.index'));
}
As you can see, I put the method update because it holds some form of validation. But whenever I try to update the data within the form of the Blade file, I get this error:
Error
Class 'App\Http\Controllers\Admin\Rule' not found
I even tried adding use Illuminate\Support\Facades\Validator; but still receives the error. How can I fix this error?
call this in your file
use Illuminate\Contracts\Validation\Rule;
enter image description herein my laravel app, i have problem that is when i register user laravel automatically fills email_verified_at column in user table and redirects to dashboard. it automatically verifies without clicking on link. I do not know why this is filling this column value while sending verification email.
this is register controller
protected $redirectTo = 'email/verify';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'alpha_num', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
this is user model
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
this is verification controller
use VerifiesEmails;
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('auth');
$this->middleware('signed')->only('verify');
$this->middleware('throttle:3,1')->only('verify', 'resend');
}
this is route file
Auth::routes(['verify' => true]);
Route::group(['prefix'=>'dashboard','middleware' => ['auth','verified']],function () {
Route::get('/','dashboard\DashboardController#index')->name('dashboard-home');
});
this is login controller
class LoginController extends Controller
{
use AuthenticatesUsers{
logout as performLogout;
}
protected $redirectTo = '/dashboard';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('prelogoutaction',['only' => 'logout']);
$this->middleware('postloginaction',['only' => 'login']);
}
public function logout(Request $request){
$this->performLogout($request);
return redirect()->route('web-home');
}
}
both email_verified_at and created_at are same.
please help...
So after all the discussion over comments and after seeing the code
we can conclude that the issue is on the database end which set the verification date and it is automatically filled up because of the attribute ON UPDATE CURRENT_TIMESTAMP() whenever the record is created.
Modify my registration blade. I added 2 additional functions that trigger the registration of the user. The data I needed are being saved to the appropriate tables but I am having this error,
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
implement interface Illuminate\Contracts\Auth\Authenticatable, boolean
given, called in
E:\wamp64\www\aftscredit-appzcoder\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
on line 35
Here's my Registration controller
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Referral;
use App\CollectorMember;
use App\HasRoles;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
public function index(Request $request)
{
$referral = '';
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if (is_null($keyword))
return view ( 'Auth.register');
elseif ($referral)
return view ( 'Auth.register', compact('referral', $referral))
->withDetails ( $referral )
->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not EXISTING or not AVAILABLE.' );
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user_id = $user->id;
Referral::find($data['referral_id'])->update ([
'status' => 1,
'date_used' => $data['referral_date_used']
]);
return CollectorMember::create ([
'collector_id' => $data['referral_generate_by'],
'borrower_id' => $user_id,
'referral_id' => $data['referral_id'],
]);
}
}
What's causing this? thanks in advance!
Try opening the RegistersUsers trait and look at line 35. A user is not being created.
The original Laravel controller code to create a user is as follows:
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Note how the DocBlock indicates an instance of User must be returned. This is key because the the actual code that completes the registration, within the trait, assumes a a valid User model instance.
It's sometimes helpful to step through the code and understand what Laravel is doing for you, behind the scenes.
In Laravel (5.8) controller, i try to make update() function for my User model.
I validate data with using my own class UpdateRequest. When i put variable $user in this class, i have error Undefined variable: user.
<?php
namespace App\Http\Requests\Users;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|alpha_dash|max:255|min:6',
'email' => ['required',
'string',
'email',
'max:255',
Rule::unique('users')->ignore($user->id)],
];
}
}
public function update(User $user, UpdateRequest $request)
{
$user->update($request->only(['name', 'email']));
return redirect()->route('users.index');
}
But if I use validate function in controller update() method, all works fine.
public function update(User $user, Request $request)
{
$this->validate($request, [
'name' => 'required|string|alpha_dash|max:255|min:6',
'email' => 'required|string|email|max:255|unique:users,id,' . $user->id,
]);
$user->update($request->only(['name', 'email']));
return redirect()->route('users.index');
}
In your custom request class, you don't have the $user initialized and you try to use it, while in the controller method the $user is passed as a parameter.
Note $this->user in the Request returns the currently authenticated user, so make sure that you always want to use his ID, instead of an ID of the passed in user, hence the reason I am using request('user') to get the user id from the URL.
So try this instead:
public function rules()
{
return [
'name' => 'required|string|alpha_dash|max:255|min:6',
'email' => ['required',
'string',
'email',
'max:255',
Rule::unique('users')->ignore(request('user'))],
];
}
You need to change $user->id to $this->user->id and it should work properly. Check below:
return [
'name' => 'required|string|alpha_dash|max:255|min:6',
'email' => ['required',
'string',
'email',
'max:255',
Rule::unique('users')->ignore($this->user->id)],
];
Hope it helps you!!
User class instance is missing in UpdateRequest class constructor or you can try with $this->user->id. It may help you.