This is what I have inside RegisterUsers.php, which is in my vendor folder:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
//$this->guard()->logout();
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
In my RegisterController, from the auth folder I have the following:
protected function create(array $data)
{
Session::flash('status', 'Please verify your email for account activation');
//if $request->role_id == '2' then save the role_id
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'verifytoken' => Str::random(40),
'role_id' => $data['role_id']
]);
$thisUser = User::findOrFail($user->id);
$this->sendEmail($thisUser);
return $user;
}
I deployed my site with forge but I just noticed that my registration does not work the same as it does on localhost.
When a user registers, the system automatically logs him in. On localhost, I had disabled the guard, but that is in the vendor folder.
Since I cannot upload the vendor folder, how exactly can I disable the guard on the live environment?
You can override the register method. The Auth\RegisterController: uses RegistersUsers; from your vendor.
So you can simply create a method like this:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Related
I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.
I'm trying to create policies for my Laravel API, so that only the the user can edit their own profile. Maybe these policies do not work the same way for API's.
Controller:
public function updateProfile(Request $request, User $user)
{
$this->authorize('updateProfile', $user->profile);
$validator = Validator::make($request->all(), [
'display_name' => 'required|unique:profiles',
]);
if ($validator->fails())
return response()->json(['error' => $validator->messages()], 422);
$user->profile->update($request->all());
return response(['message' => 'Profile sucessfully updated']);
}
Policy
public function updateProfile(User $user, Profile $profile)
{
return $user->id === $profile->user_id;
}
AuthServiceProvider
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
Profile::class => ProfilePolicy::class
];
They return 403 errors. I'm thinking maybe I need to use requests, instead of the user models in the policy? like
$request->user->id === $request->profile->user_id
Any idea what the issue is?
In my Laravel application, after a new registration, it connects automatically to this new account.
I just need to register and stay connected with the actual Auth Account. How can we change this default setting?
Because I'm creating new accounts in the application with the admin user.
Thank you
This is my registerController code:
use RegistersUsers;
protected function redirectTo()
{
if(Auth::user()->is_admin == 1){
return 'persons';
}
return '/persons';
}
public function __construct()
{
$this->middleware('auth');
}
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:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
In Registeruser.php I changed the function register to
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Note please that I create new users using person.blade.php, and not /register
In your App/Http/Controllers/Auth/RegisterController you need to override the method register from RegistersUsers trait:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
This line: $this->guard()->login($user); is where the user gets logged in. You can either remove it or modify it to suit your needs.
Now if you want to redirect after registration to a certain place depending on type of user you'd need to replace protected $redirectTo to:
protected function redirectTo()
{
//You would need to modify this according to your needs, this is just an example.
if(Auth::user()->hasRole('admin')){
return 'path';
}
if(Auth::user()->hasRole('regular_user')){
return 'path';
}
return 'default_path';
}
On top of your file, add these:
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
I am working in laravel and i am using the spatie permission package
and I want to assign the different role for the user while registration I am using the radio button to get the role from a user such as editor ,writer,blogger
how to I assign the different role to user based on the user input
In Laravel Auth\RegisterController you can modify the create() function.
This is valid if you are using Spatie package.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->assignRole('customer'); //assign role to user
return $user;
}
Take that user input and use assignRole function as described in the package readme file
Something like
public function someController(Request $request)
{
....
$user->assignRole($request->input('role'));
...
}
assuming you have a form input (checkbox, radio, text) with name role
I have finally found a way to attach the different role to the user based on the user selection
In my register create function
$role = $data['userType'];
if ($role == 'User') {
$user->assignRole('User');
}elseif ($role =='Vendor') {
$user->assignRole('Vendor');
}
You can try the following code:
protected function create(array $data)
{
$user=User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'user_name' => $data['user_name'],
'role_name' => $data['role_name'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role_a = $data['role_name'];
if($role_a == 'student') {
$role = Roles::select('id')->where('admin_name', 'student')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'clg_admin'){
$role=Roles::select('id')->where('admin_name','clg_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'univ_admin'){
$role=Roles::select('id')->where('admin_name','univ_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'gov_admin'){
$role=Roles::select('id')->where('admin_name','gov_admin')->first();
$user->roles()->attach($role);
return $user;
}
elseif ($role_a == 'hod'){
$role=Roles::select('id')->where('admin_name','hod')->first();
$user->roles()->attach($role);
return $user;
}
}
Will try make this clear as much as I can.
Im rolled out a make Auth call in order to use the login and registeration function of laravel and later just used the template to provide the needs I wanted that is.
If user is admin he/she can register a new user.
public function openNewUser(){
return view('auth.register');
}
NB. Part for update.
public function registerNewUser(Request $request){
$this->validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::denies('register-user')) {
return redirect()->back();
}
$user->save();
return view('home');
}
Problem 1 - I also want to update user , which is giving problems. The password inputs return empty fields , which i understand. When I try to change it doenst work the confirm password always give a mismatch even though they are the same. When I leave it blank too it doesnt work because the field is required to be filled. I took them off the form and tried if i could edit the email only but only didnt work.
public function userUpdate (Request $request,$user_id) {
$this->validate($request,[
'email' => 'required|email',
'name' => 'required|max:120',
'password' => 'required|min:4|confirmed']);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = encrypt($request->password);
if (Gate::allows('register-user')) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}elseif (Gate::denies('register-user')) {
if (Auth::id() == $user_id) {
$user->save();
$user->roles()->attach($request->roles);
return redirect()->route('view_users');
}else{
return redirect()->back();
}
}
}
Problem 2. I just realized all logins I am doing with my new registration gives These credentials do not match our records.Even though the credentials are there and was registered correctly.
I am using the login provided by laravel but I created my own registration.
Please how can I edit and update my users and also be able to login after registration
What version of Laravel are you using?
Here is my (v5.3) register() method in RegisterController.php, at least part for registration:
public function register(Request $request)
{
...
// save and login user
$user = $this->create($request->all());
$this->guard()->login($user);
...
}
...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
and the login() method from LoginController.php
public function login(Request $request)
{
$credentials = $this->credentials($request);
...
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
}
Hopefully I haven't miss anything.
Keep in mind that things have changed here from version 5.2.
I found out what was wrong , Since I am using Laravel's login my registration had to use bycrypt for the encryption which is what Laravel registration was using , but I was using encrypt when I created my own registration so there was a conflict when logging in. (Remembere I was using Laravels login not my own written Login). I hope this helps someone