Laravel get id of latest inserted user - php

I'm using the Laravel Auth to make users able to register. What I'm now trying is: After users register (if they have a special role selected), there is another row inserted into another table (then users) which holds the relating user id. This is the code for it:
<?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 App\Complaint;
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)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'username' => 'required|unique:users',
'role' => 'required'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->username = $data['username'];
$user->password = bcrypt($data['password']);
$user->role = $data['role'];
$user->templateURL = "";
/*$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
'role' => $data['role'],
'templateURL' => ""
]);*/
$user->save();
if($data['role'] == 'Verkäufer'){
$complaintRow = Complaint::create([
'user_id' => $user->id,
'complaintCount' => 0
]);
}
switch($data['role']){
case 'Käufer':
$user->attachRole(2);
break;
case 'Verkäufer':
$user->attachRole(3);
break;
default:
$user->attachRole(2);
break;
}
return $user;
}
}
But it's not working correctly, the user is inserted as well as a row for the complaints, but somehow $user->id seems to be null, the column always has user_id set to 0. Any ideas why this could be like this?
EDIT: I got it working now... It was actually not the code I posted, I just didn't make the user_id field fillable in the complaint table, that's why there was 0 in always, because 0 was the default value, so it just didn't set it.
Thanks all for the answers anyway.

As per Laravel Eloquent ORM, $user->id will return the Id of user.
If you are getting null, then there might be error in saving. (https://stackoverflow.com/a/21084888/6628079)
Try printing $user after saving it.
UPDATE:
It would be better if you add data in complaint table if user is saved successfully.
protected function create(array $data)
{
$user = new User;
$user->name = $data['name'];
$user->email = $data['email'];
$user->username = $data['username'];
$user->password = bcrypt($data['password']);
$user->role = $data['role'];
$user->templateURL = "";
/*$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
'role' => $data['role'],
'templateURL' => ""
]);*/
if ($user->save()) {
if ($data['role'] == 'Verkäufer') {
$complaintRow = Complaint::create([
'user_id' => $user->id,
'complaintCount' => 0
]);
}
switch ($data['role']) {
case 'Käufer':
$user->attachRole(2);
break;
case 'Verkäufer':
$user->attachRole(3);
break;
default:
$user->attachRole(2);
break;
}
return $user;
} else {
// Your code if user doesn't save successfully.
}
}

This is because, Eloquent save method bool but not the instance of newly created Entity. For confirmation checkout this link: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html
So, if you want to get the newly created instance you can either user create method or make another query to get newly inserted instance. First one is better ans easy. Here is how you can do it:
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
'role' => $data['role'],
'templateURL' => ""
]);
Now, you have $user variable containing User instance. But to do this you need to consider fillable/guared issue in your model. I mean, in your model you have to add the following line:
protected $fillabe = ['name', 'email', 'username', 'password', 'role', 'templateURL']

Is column id exists?
Try to set $primaryKey = 'id' on model (user).
After $user->save you can access to id like $user->id
Or after $user->save try to get max id from your table.
$user = User::select('id')->max('id')->first();

Try this:
$lastId = User::create($userData)->id;

$user->id will tell you created user's ID right after using save() method.

You did all most correct you just need to change,
when you are saving user object it will return saved user object so just grab that object and use in furcher conditions.
$saved_user = $user->save();
if(!empty($saved_user)){
if($data['role'] == 'Verkäufer')
{
$complaintRow = Complaint::create([
'user_id' => $saved_user->id,
'complaintCount' => 0
]);
}
} else {
throw new error(500);
}
Hope this will help thanks :)

Related

Laravel Socialite For Different Role User

I'm creating a project with two user roles.
I use the role_id field to distinguish roles from users.
When a user registers an account via manual input I make use of the hidden input to store the role_id.
But how can I save the role_id of users when they register for an account using a google account?
This is my controller
public function redirect($provider)
{
return Socialite::driver($provider)->redirect();
}
public function callback($provider)
{
$getInfo = Socialite::driver($provider)->user();
$user = $this->createUser($getInfo, $provider);
auth()->login($user);
return redirect()->to('/');
}
function createUser($getInfo, $provider){
$user = User::where('provider_id', $getInfo->id)->first();
if(!$user) {
$user = User::create([
'name' => $getInfo->name,
'email' => $getInfo->email,
'provider' => $provider,
'provider_id' => $getInfo->id,
'email_verified_at' => Carbon\Carbon::now()
]);
}
return $user;
}
This is my route
Route::get('/auth/redirect/{provider}/', 'LoginUserController#redirect');
Route::get('/callback/{provider}/', 'LoginUserController#callback' );
My View
a href="{{ url('/auth/redirect/google') }}" class="link-custom">{{ __('Google Account') }}</a>
It is not entirely clear how you save the user role. Is it in a different table? On which basis do you assign roles to users? Nevertheless, you could always adjust the createUser method and save the other related info after creating the user. For example:
private function createUser($getInfo, $provider){
$user = User::where('provider_id', $getInfo->id)->first();
if(!$user) {
$user = User::create([
'name' => $getInfo->name,
'email' => $getInfo->email,
'provider' => $provider,
'provider_id' => $getInfo->id,
'email_verified_at' => Carbon\Carbon::now()
]);
// Here you can save other stuff,
// E.g. the user role supposing it is saved in a different table
UserRole::create([
'user_id' => $user->id,
'role_id' => 1 // Assigned role id
]);
}
return $user;
}
Two things you need to consider:
Don't use hidden field to store a role_id. What's up with an user edit the code inline and change the role_id?
You should to set up a default value for the role_id field, then all the users will have that default role.

Cookie::get() return null

I have problems getting Cookie, I define a cookie in one middleware "CheckReferral", but when I call the cookie in one Controller the cookie return null, I check the cookie in the browser, and the cookie is good in the browser, I don't know what is the problem with the cookie... I've googled too much and this is my last resource, Someone can help me?
Here is the code of the middleware:
<?php
namespace App\Http\Middleware;
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 how I call the cookie in the controller:
protected function create(array $data)
{
// $referred_by = User::where( 'affiliate_id', Cookie::get( 'referral' ) )->first();
// $referred_user = Cookie::get( 'referral' );
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => $this->uniqueRandomString(),
'referred_by' => Cookie::get('referral'),
]);
}
Here is the cookie stored in the browser:
Here is the database... the field referred_by, is stored as null, but should store the Value of the cookie:
Thank a lot, I hope resolve the problem, and know the cause...
Make sure you've defined that middleware in app\Http\Kernel.php. Specifically in the 'web' array there.
Imported the middleware in your web.php ( routes ) file.
..and finally added that middleware for your route like so:
Route::web('/', ['middleware' => CheckReferral']
If you've already done so then make sure you've added referred_by column to the $fillable[] array of your User model.
Edit.
This will do:
\Request::cookie('referral');
I've solved it using vanilla PHP, the global variable $_COOKIE
protected function create(array $data)
{
// $referred_by = User::where( 'affiliate_id', Cookie::get( 'referral' ) )->first();
// $referred_user = Cookie::get( 'referral' );
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'affiliate_id' => $this->uniqueRandomString(),
'referred_by' => $_COOKIE['referral'],
]);
}
Where Cookie::get('referral') is $_COOKIE['referral'] is not a Elegant solution, but work...

Laravel 5.2 Storing data in another Database after Registration

Im using the default registration and log in form of laravel. What i want to happen is how do i store a data after the user successfully register. I tried doing this but its not storing any data in the Time_tracker table and there is no any error occured. Can some one help me?
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Illuminate\Mail\Mailer;
use Illuminate\Http\Request;
use App\Time_tracker;
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 = 'maintenance';
/**
* 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, [
'name' => 'required|max:255',
'company' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'telephone' => 'required|max:255',
'password' => 'required|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)
{
return User::create([
'name' => $data['name'],
'company' => $data['company'],
'email' => $data['email'],
'telephone' => $data['telephone'],
'password' => bcrypt($data['password']),
]);
$user = new Time_tracker;
$user->current_time = 0;
$user->purchase_time = 0;
$user->status = 'not_paid';
$user->user_id = $id;
$user->save();
}
}
You are returning the created user that's why the code below it isn't running, you should remove return and place it at the end in this way:
protected function create(array $data)
{
$user = User::create([ // <------ Removed 'return' from the front of this line
'name' => $data['name'],
'company' => $data['company'],
'email' => $data['email'],
'telephone' => $data['telephone'],
'password' => bcrypt($data['password']),
]);
$time_tracker = new Time_tracker();
$time_tracker->current_time = 0;
$time_tracker->purchase_time = 0;
$time_tracker->status = 'not_paid';
$time_tracker->user_id = $user->id; // <----- This would be '$user->id' instead of '$id'
$time_tracker->save();
return $user; // <----- 'return' added at the end of the method
}
Hope this helps!

Insert in two tables when registering users in Laravel

I'm using the default Laravel 5.1 user registration. I have two tables: users and shops. When user registers, the app should insert a user in the table users, get the id and use it to register a shop. I've been reading the default AuthController.php but i didn't find anything. Here is the AuthController if it helps.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
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;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* 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|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* 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']),
]);
}
/**
* Get the path to the login route.
*
* #return string
*/
public function loginPath()
{
return route('login');
}
/**
* Get the post register / login redirect path.
*
* #return string
*/
public function redirectPath()
{
return route('home');
}
}
Solved, but now I have a Integrity constraint violation. Is this code correct?
protected function create(array $data)
{
$user = new User([
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
$user->role = 'shop_owner';
$user->remember_token = str_random(10);
$user->save();
$userId = $user->id;
Shop::create([
'name' => $data['s_name'],
'address' => $data['s_address'],
'CP' => $data['s_pcode'],
'Telephone' => $data['s_tlf'],
'contact_name' => $data['cp_name'],
'contact_num' => $data['cp_tlf'],
'id_user' => $userId
]);
return $user;
}
There you go:
protected function create(array $data)
{
$user = User::create([
//'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$userId = $user->id;
Shop::create([... use $userId here ...]);
return $user;
}
This goes to your controller:
public function store(Request $request) {
$user = User::create(Input::all());
$user->save();
$shop = Shop::create([..enter shop attributes or leave blank..]);
$user->shop()->save($shop);
}
You need to place the following code at the top of the Auth Controller
use App\Shop;

How i can assign a role to a user during signup? ( Entrust ) ( Laravel 5.1 )

I have just installed in my laravel 5.1 project the entrust package you can find this package here Entrust Package Github .
I want to assign a role to a user after the sign up post button because after that each user will complete a different profile. You can see the AuthController.php above.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectPath = '/';
protected $loginPath = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
/**
* 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|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
'role' => 'required|',
]);
}
/**
* 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']),
'role' => $data['role'],
]);
$tutorschoolRole = DB::table('roles')->where('name', '=', 'Φροντιστήριο')->pluck('id');
$studentRole = DB::table('roles')->where('name', '=', 'Μαθητής')->pluck('id');
$teacherRole = DB::table('roles')->where('name', '=', 'Καθηγητής')->pluck('id');
$parentRole = DB::table('roles')->where('name', '=', 'Γονέας')->pluck('id');
if(User::role == "Φροντιστήριο"){
User::roles()->attach($tutorschoolRole);
}
if(User::role == "Μαθητής"){
User::roles()->attach($studentRole);
}
if(User::role == "Καθηγητής"){
User::roles()->attach($teacherRole);
}
if(User::role == "Γονέας"){
User::roles()->attach($parentRole);
}
}
}
Delete the role column from the users table and migrate Entrust tables using this command.
php artisan entrust:migration
The 4 tables will be created:
roles — stores role records
permissions — stores permission records
role_user — stores many-to-many relations between roles and users
permission_role — stores many-to-many relations between roles and
permissions
From your DB, you can add roles and permissions manually. The simple way to attach the role to the user.
$admin = new Role();
$admin->name = 'admin';
$admin->display_name = 'User Administrator'; // optional
$admin->description = 'User is allowed to manage and edit other users'; // optional
$admin->save();
$user = User::find(1);
$user->attachRole($admin); // parameter can be an Role object, array, or id
I solved this, i had to return the user in the end.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role' => $data['role'],
]);
$role_value = $user->role;
$id = 0;
if($role_value == 'Φροντιστήριο')
$userRole = DB::table('roles')->where('name', '=', 'Tutorschool')->pluck('id');
if($role_value == 'Μαθητής')
$userRole = DB::table('roles')->where('name', '=', 'Student')->pluck('id');
if($role_value == 'Καθηγητής')
$userRole = DB::table('roles')->where('name', '=', 'Teacher')->pluck('id');
if($role_value == 'Γονέας')
$userRole = DB::table('roles')->where('name', '=', 'Parent')->pluck('id');
$user->roles()->attach($userRole);
return $user;
}

Categories