I'm using laravel and I want to make auth register and checking by email and provider. Use email and provider because users can register if users login with social media (ex:facebook) have same email like users login with email. I can only make checking by email.
this is my Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'username' => 'required|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'provider' => 'unique:users',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
// $prov = 'Email';
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'provider' => 'Email',
]);
}
}
Related
I created a registration form with the use of laravel ui scaffolding.
What I did:
• Added some field besides the default ones
• Using the auth controller specifically RegisterController and change a part of the create function from this
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Into this:
protected function create(array $data)
{
return User::create([
'user_email' => $data['email'],
'user_Type' => $data['user_Type'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'contact_number' => $data['contact_number'],
]);
}
But the result after submitting the form with a post method is this:
ArgumentCountError
Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed in /Users/idan/Documents/SweetSurrender/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 and exactly 1 expected
Web.php
Route::get('/register', function() {
return view('auth.register');
})->name('register');
Route::post('/register', [RegisterController::class, 'create']);
RegisterController.php
<?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
{
/*
|--------------------------------------------------------------------------
| 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
*/
public function index() {
return view('auth.register');
}
protected function validator(array $data)
{
return Validator::make($data, [
'username' => ['required', 'string', 'max:16'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'contact_number' => ['required', 'string', 'min:12', 'unique:users'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'user_email' => $data['email'],
'user_Type' => $data['user_Type'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'contact_number' => $data['contact_number'],
]);
}
}
I also tried using this in RegisterController.php
protected function create(Request $data)
{
return User::create([
'user_email' => $data->input('email'),
'user_Type' => $data->input('user_Type'),
'username' => $data->input('username'),
'password' => Hash::make($data->input('password')),
'contact_number' => $data->input('contact_number'),
]);
}
but it results to an error:
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1364 Field 'user_email' doesn't have a default value (SQL: insert into users (password, updated_at, created_at) values ($2y$10$vr7UasRBCzx2URQxLSWneuvr4Hl1at.q7qDk8UK0Wc/INjeHeYH7y, 2020-12-22 07:15:41, 2020-12-22 07:15:41))
I solved this problem by using the same code:
protected function create(array $data)
{
return User::create([
'user_email' => $data['email'],
'user_Type' => $data['user_Type'],
'username' => $data['username'],
'password' => Hash::make($data['password']),
'contact_number' => $data['contact_number'],
]);
}
and In the User model I included this:
protected $fillable = [
'username',
'user_email',
'password',
'contact_number',
];
I am getting an error while trying to Auto Login After successful registration in laravel 6 getting the following error.
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in
My Registercontroller is
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
// $this->middleware(['auth','verified']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'min:3'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$username = slugify($data['name'])."-".mt_rand(10000, 99999);
$user = User::create([
'name' => $data['name'],
'username' => $username,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'email_token' => base64_encode($data['email']),
]);
Auth::loginUsingId($user->id);
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Jobs\SendEmailJob;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email','name','password','username','picture',
'ip_address','email_verified_at','email_token','verified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function socialProviders(){
return $this->hasMany(socialProvider::class);
}
// This is the code define in the sendEmailVerificationNotification
public function sendEmailVerificationNotification()
{
SendEmailJob::dispatch($this);
}
}
You have overwritten the registration logic, but you have ignored the fact that create method needs to return an instance of App\User - or at least a class that implements Authenticatable.
Take a look at the original logic; you will see that the docblock shows that an instance of App\User is being returned and that the original implementation returns the result of the User::create() call.
To get your custom method working, update it like so:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => slugify($data['name'])."-".mt_rand(10000, 99999);,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'email_token' => base64_encode($data['email']),
]);
}
Laravel will take care of logging the user in by default anyway.
I am trying to do registration of multi-user in my registration controller and used the following code and checked. But it shows me error:
Method App\Http\Controllers\Auth\RegisterController::validator does not exist.
<?php
namespace App\Http\Controllers\Auth;
use App\Admin;
use App\Manager;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
public function __construct()
{
$this->middleware('guest');
$this->middleware('guest:admin');
$this->middleware('guest:manager');
}
protected function createAdmin(Request $request)
{
$this->validator($request->all())->validate();
$admin = Admin::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/admin');
}
protected function createManager(Request $request)
{
$this->validator($request->all())->validate();
$manager = Manager::create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password']),
]);
return redirect()->intended('login/manager');
}
}
Try to add validator() function like follow:
protected function validator(array $data, $table)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:'.$table],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
then you can make validation like so:
$this->validator($request->all(), 'table_name')->validate();
change table_name with corresponding name.
my controller is RegisterController which is in controller in auth folder
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\User;
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 = '/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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(Request $request)
{
$this->validate($request, [
'first_name' => 'required|max:255',
'middle_name' => 'string|max:255',
'last_name' => 'required|max:255',
'email' => 'required|max:255|unique:users',
'password' => 'required|min:6|',
'user_status' => 'required|max:255',
'user_role' => 'required|max:255',
'user_type' => 'required|max:255',
'phone' => 'required|max:255',
'address' => 'required|max:255',
]);
return User::create([
'first_name' => $request['first_name'],
'middle_name' => $request['middle_name'],
'last_name' => $request['last_name'],
'email' => $request['email'],
'password' => bcrypt($request['password']),
'user_status' => $request['user_status'],
'user_role' =>$request['user_role'],
'user_type' =>$request['user_type'],
'phone' =>$request['phone'],
'address' =>$request['address'],
]);
}
public function index(){
return User::all();
}
}
And my api.php file in routes folder is
Route::get('/users','Auth\RegisterController#index')->middleware('auth');
I want to all data from user table which code is in Auth\Regitercontroller in index function this route returns
{
"error":"unauthenticated",
}
so i want aall user from table user and if i remove middleware->('auth:api') from routes then i got all users but i want middleware in routes for security reason so help me.Thank You
I'm trying to find out why when I dd($request->all()) in the store method of my controller everything is correct, however when I send it to the model function register() its no where to be seen.
I'm not quite sure what I'm doing wrong.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function store(Request $request, User $user)
{
$this->authorize('delete', $user);
$this->validate($request, [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
$userRegistered = $user->register(
new User($request->all())
);
if ($userRegistered) {
flash()->success('Success', 'The user has been successfully created!');
} else {
flash()->error('Error', 'The user could not be successfully created!');
}
return redirect()->to(route('users'));
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use SoftDeletes;
/**
* Fillable fields for a user.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'display_name',
'email',
'password',
'role_id'
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function register(User $user)
{
return $user->create([
'first_name' => $user->firstName,
'last_name' => $user->lastName,
'display_name' => $user->displayName,
'email' => $user->emailAdress,
'password' => $user->password,
'role_id' => $user->role
]);
}
}
You've mixed up the formatting of your variables between your request data and your User model.
According to your validation logic, the request data is coming is as camelCase. Yet, according to your $fillable array, the fields on your User model are snake_case. But, even then, in your register method, you're attempting to access the fields on the User model using camelCase.
You haven't given enough information for a definitive answer, but you need to fix the formatting of your variables. For example, change your request fields names from camelCase to snake_case, and make sure you access your fields on the model using snake_case.
You have to pass a list of attributes to "validate" method.
//...
$this->validate($request->all(), [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
One more thing..check if you are using "web" middleware. (Kernel.php => MiddlewareGroups). Add that middleware to your route.