I am building a system where the Admin can add users. That being said my Auth controller looks like this, which works great, but using the standard registration the user gets logged in after creation. Obviously if the Admin adds a users (another admin or just a general user) the admin wants to remain logged in and not log in the user just created. How can I do this in a manner where I dont have to edit any of the library? If I update Laravel that would overwrite those changes.
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Role;
use Mail;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image as Image;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/add';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first-name' => 'required|max:255',
'last-name' => 'required|max:255',
'phone' => 'required|max:255',
'form' => 'max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create( array $data )
{
//Create the user
$user = User::create([
'first_name' => $data['first-name'],
'last_name' => $data['last-name'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
//Is it a User? Then give them that role
if ($data['user-role'] == 'user')
{
$role = Role::where('name', '=', 'user')->firstOrFail();
$user = User::find($user->id);
$user->roles()->attach($role->id);
}
//Is it an Admin? Then give them that role
if ($data['user-role'] == 'admin')
{
$role = Role::where('name', '=', 'owner')->firstOrFail();
$user = User::find($user->id);
$user->roles()->attach($role->id);
}
Mail::send('auth.emails.registered', ['user' => $user], function ($m) use ($user)
{
$m->to($user->email, $user->first_name)->subject('You Have Been Added');
});
return $user;
}
}
The RegisterUsers trait, used on registration, automatically logs users in the register() method, but you can safely overwrite it in the AuthController like this:
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$this->create($request->all());
return redirect($this->redirectPath());
}
Related
I have this on my controller but the redirection does not work it says Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login(), I have tried this so far but nothing
<?php
namespace App\Http\Controllers\Auth;
use App\Events\NewUserWasRegistered;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Validator;
use Auth;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
*
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$rules = [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'g-recaptcha-response' => 'required|captcha',
'allow_register' => 'required|accepted',
];
if (app()->environment('local') || app()->environment('testing')) {
unset($rules['g-recaptcha-response']);
}
$data['allow_register'] = config('root.app.allow_register', true);
$messages = [
'allow_register.accepted' => trans('app.allow_register'),
];
return Validator::make($data, $rules, $messages);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
*
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'username' => md5("{$data['name']}/{$data['email']}"),
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id' => $data['role'],
]);
event(new NewUserWasRegistered($user));
if($user){
if ($user->role_id == 0) {
Auth::login($user);
return redirect('user/businesses');
}else if($user->role_id == 1){
Auth::login($user);
return 'Working on..';
}
}
// return $user;
}
}
Can someone please help me I am stuck, I have tried so many things but I am new on coding so maybe you will understand If it is that I am asking too much
App\Models\User must implement the interface/contract Illuminate\Contracts\Auth\Authenticatable.
"If you need to log an existing user instance into your application, you may call the login method with the user instance. The given object must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract. Of course, the App\User model included with Laravel already implements this interface ..."
Laravel 5.7 Docs - Authentication - Manually Authenticating Users - Other Authentication Methods
Side Note:
The create method of that controller is only for taking an array of data and creating a new User and returning that User instance. Nothing else. The registration flow out of the box calls that method, only to create the user. It then does the login and everything else.
Using laravel5.3
php 5.6.3
I want the last inserted id in users table for the redirected page after registration
So I want the last inserted id to userprofileadd.blade.php
I have also tried ->with('id', $user->id) from register function
I don't want automatic login after registration , so I removed the login part , and after registration the user will be redirected to another form , and i want the latest user id (who ever registered) from users table
Register controller:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\role;
use App\Userdetails;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/userprofileadd';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware(['auth', 'hr']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'role'=>'required'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id'=>$data['role'],
]);
}
public function showregistrationform()
{
$roles = role::all(); // get all teams
return view('auth.register', [ 'roles' => $roles]);
}
}
register function (i have commented out login after registration)
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());
// ->with('id', $user->id)
}
if you are using model then
$user = new User();
$user->name = "JOHN";
$user->save();
$user->id; // contain the inserted id
if you are using db class
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
To get the last created user
$user = User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id'=>$data['role'],
]);
$this->lastCreatedUserId = $user->id;
To pass the userId to custom redirection page
You may use the Laravel Auth redirectTo method. Doc.
protected function redirectTo()
{
return route('customroutename', ['id' => $this->lastCreatedUserId]);
}
Example:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\role;
use App\Userdetails;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
public $lastCreatedUser;
use RegistersUsers;
protected $redirectTo = '/userprofileadd';
//The redirectTo method will take precedence over the redirectTo attribute.
protected function redirectTo()
{
//assuming your route name is 'userprofileadd' if not, use your route name of the route('/userprofileadd')
return route('userprofileadd', ['id' => $this->lastCreatedUser]);
}
public function __construct()
{
$this->middleware(['auth', 'hr']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'role'=>'required'
]);
}
protected function create(array $data)
{
$user = User::create([
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id'=>$data['role'],
]);
$this->lastCreatedUser = $user->id;
return $user;
}
public function showregistrationform()
{
$roles = role::all(); // get all teams
return view('auth.register', [ 'roles' => $roles]);
}
}
You can access the last created user in your UserprofileController's index method like,
public function index($id)
{
$lastCreatedUser = $id;
//you may pass this variable to the view
}
Hope it helps.. Let me know the results..
I'm not sure if this is what you're looking for or not, but you can do this to retrieve the latest record in the users table:
$latestUser = App\User::latest()->first();
Hopefully this helps.
I've made a referral system on my laravel project v5.4 but I have 2 issues with that:
My users referral link will load index page of my website instead of loading register page. (How I fix it?)
When user register with referral link nothing will happen in database of the person who invited new user and also new user him/herself. (How I get info in both users tables?)
I simply used this tutorial to get my referral system:
https://brudtkuhl.com/building-referral-system-laravel/
This is my CheckReferral Middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Response;
use Closure;
class CheckReferral
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if( $request->hasCookie('referral')) {
return $next($request);
}
else {
if( $request->query('ref') ) {
return redirect($request->fullUrl())->withCookie(cookie()->forever('referral', $request->query('ref')));
}
}
return $next($request);
}
}
This is my UserController
public function referral() {
$user = User::find(1);
return view('users.referral', compact('user'));
}
Here is my route:
Route::get('/referral', 'UserController#referral')->name('referral');
My RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Cookie;
use DB;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'username' => 'required|string|max:255|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'g-recaptcha-response' => 'required|captcha',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$referred_by = Cookie::get('referral');
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => str_random(10),
'referred_by' => $referred_by,
]);
}
User Model
protected $fillable = [
'name', 'username', 'email', 'password', 'affiliate_id', 'referred_by',
];
And That's it!
if this is for registration the right way to do this is first in your routes you should have a optional input like ..
Route::get('/register/{referral?},'Auth\RegisterController#registerPage');
then in that controller
public function registerPage($referral=0)
{
return view with the $referral variable ..
}
in your view .. your form should look like this ..
<form action="/register/{{ referral }}" method="post" ..... >
back to your route ..
Route::post('/register/{referral},'Auth\RegisterController#doRegister');
in your controller again ..
public function doRegister(Request $request, $referral)
{
$request->merge(['referred_by' => $referral]);
}
so your referred_by is either 0 or other value .. it's up to you how you handle the validation ..
Add register page url in the value in this part -> url('/')
#if(!Auth::user()->affiliate_id)
<input type="text" readonly="readonly"
value="{{url('/').'/?ref='.Auth::user()->affiliate_id}}">
#endif
Question number 1:
I think you should add {{url('/register')}} here instead of {{url('/')}} to make it look this way:
#if(!Auth::user()->affiliate_id)
<input type="text" readonly="readonly"
value="{{url('/register').'/?ref='.Auth::user()->affiliate_id}}">
#endif
If that's how your register route endpoint is defined.
How can I redirect to login page, after a user is registered on my web application with a message called "Your information is received and witing for admin approval.". By using laravel 5.4 version
Note: I have done the login and register by using Auth procress of laravel 5.4.
Edit: Here is my RegisterController
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Storage;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/login';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
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',
'userimage' => 'required|image'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data) {
$path = Storage::putFile('userimages',$data['userimage']);
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'userimage' => $path,
'user_type' => 3
]);
return $user;
}
In RegisterController, by default Laravel login the user, so when you redirect back to login route. It gives you page is not redirecting properly error.
In your RegisterController add the register method :
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
return redirect($this->redirectPath())->with('message', 'Your message');
}
Also add this line of code on the top of RegisterController:
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
Recently I add email verification in my Web App from this blog post
My app is working good and I also get an email when user signup but when I try to login without activated I must get an other email from my app but it won't send it. I'm missing something but I didn't find help to resolve this.
This is my AuthController
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\ActivationService;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $activationService;
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
public function __construct(ActivationService $activationService)
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
$this->activationService = $activationService;
}
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$user = $this->create($request->all());
$this->activationService->sendActivationMail($user);
return redirect('/login')->with('status', 'We sent you an activation code. Check your email.');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function authenticated(Request $request, $user)
{
if (!$user->activated) {
$this->activationService->sendActivationMail($user);
auth()->logout();
return back()->with('warning', 'You need to confirm your account. We have sent you an activation code, please check your email.');
}
return redirect()->intended($this->redirectPath());
}
public function activateUser($token)
{
if ($user = $this->activationService->activateUser($token)) {
auth()->login($user);
return redirect($this->redirectPath());
}
abort(404);
}
}