Laravel 5.3 get last insert id after registration - php

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.

Related

Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated()

Help me understand and solve such errors.
ERROR :
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Type error: Argument 1 passed to App\Http\Controllers\Auth\LoginController::authenticated() must be an instance of App\Http\Controllers\Auth\Request, instance of Illuminate\Http\Request given, called in C:\proj\easywash\vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesUsers.php on line 104
Login Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except'=> ['logout','userLogout']]);
}
public function authenticated(Request $request, $user)
{
if (!$user->verified) {
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 userLogout()
{
Auth::guard('web')->logout();
return redirect('/home');
}
}
Register Controller :
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Mail\VerifyMail;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use App\VerifyUser;
use Auth;
use DB;
use Mail;
use Illuminate\Http\Request;
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',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$verifyUser = VerifyUser::create([
'user_id' => $user->id,
'token' => str_random(40)
]);
Mail::to($user->email)->send(new VerifyMail($user));
return $user;
}
public function verifyUser($token)
{
$verifyUser = VerifyUser::where('token', $token)->first();
if(isset($verifyUser) ){
$user = $verifyUser->user;
if(!$user->verified) {
$verifyUser->user->verified = 1;
$verifyUser->user->save();
$status = "Your e-mail is verified. You can now login.";
}else{
$status = "Your e-mail is already verified. You can now login.";
}
}else{
return redirect('/login')->with('warning', "Sorry your email cannot be identified.");
}
return redirect('/login')->with('status', $status);
}
protected function registered(Request $request, $user)
{
$this->guard()->logout();
return redirect('/login')->with('status', 'We sent you an activation code. Check your email and click on the link to verify.');
}
}
I also had the same problem as you and I solved that with this answer.
ANSWER
Change your use statement at LoginController:
use Illuminate\Http\Request;
// And try to comment out the next line
// use App\Http\Requests;
You're overriding this method from the AuthenticatesUsers trait, which receives a Illuminate\Http\Request, not a App\Http\Controllers\Auth\Request
directory -> app -> controller -> Auth -> RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);`enter code here`
}
control+x code and control+v on User Model
so use terminal php artisan route:list

Building a Referral System with Laravel

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.

laravel 5.2 dont log in user after registration

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());
}

Not getting email on second request email verification

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);
}
}

laravel inserting into multiple tables

I have 2 tables
#something - id, name, url
#something_users - id, id_something, email, password
My models
class Something extends Eloquent
{
protected $table = 'something';
protected $fillable = ['name', 'email', 'password'];
public $errors;
public function User()
{
return $this->belongsTo('User', 'id', 'id_something');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function Something()
{
return $this->belongsTo('Something');
}
}
Controller
$input = Input::all();
// also some validation
$this->db->fill($input);
$this->db->password = Hash::make(Input::get('password'));
$this->db->push();
$this->db->save();
SQL
insert into `something` (`name`, `email`, `password`) values...
I need to insert name into the first table(something) and email, password into second(something_users)
How to do that? I have on clue about that.
Your relationships are a little screwed up, you probably want to change those. Note the hasMany() vs the belongsTo(). If a something can only have one user, you may wish to change the function to hasOne() from hasMany() and the name of the function to user() only because it makes more sense that way.
class Something extends Eloquent {
protected $table = 'something';
public function users()
{
return $this->hasMany('User', 'id_something');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'something_users';
protected $hidden = array('password', 'remember_token');
public function something()
{
return $this->belongsTo('Something', 'id_something');
}
}
And then to save a something and a user and have them linked, it's pretty easy.
$something = new Something;
$something->name = Input::get('name');
$something->url = Input::get('url');
$something->save();
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$something->users()->save($user);
I'm not seeing your constructor so I don't know which model $this->db refers to, but you may want to replace the somethings or users depending on what you have. To keep your dependency injection going, I'd suggest naming your dependencies what they actually are.
class SomeController extends BaseController {
public function __construct(User $user, Something $something)
{
$this->user = $user;
$this->something = $something;
}
public function someFunction()
{
$this->something->name = Input::get('name');
$this->something->url = Input::get('url');
$this->something->save();
$this->user->email = Input::get('email');
$this->user->password = Hash::make(Input::get('password'));
$this->something->users()->save($this->user);
}
}
Laravel 6.
I want to add data to users table and customer table using one controller that is RegisterController.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Customer;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
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 = RouteServiceProvider::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'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
//this part is my code
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'role' => '2',
]);
$customer = Customer::create([
'user_id' => $user['id'],
'firstname' => $data['name'],
'lastname' => $data['name'],
'email' => $data['email'],
'address' => '',
'phone' => '',
'gender' => '',
]);
return $user;
}
}
enter image description here
enter image description here
This answer is not the best one, because this answer is just a shortcut code so that my code is not error. maybe another error will appear in the future.
but I hope my answer can solve your problem

Categories