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.
Related
Recently I have decided to add another field when in log in page( Username ), it is unique.
When log in you can use either username or email to do so.
After the modification, "Login", "Registeration", "Changing Password", "Password Reset", "Email Verification" worked fine.
"Two Factor Authentication", "Browser Sessions", "Delete Account" does not working just wondering what has gone wrong
When i try to delete account or log out from all browser session, this pops out
for more detailed error https://flareapp.io/share/17DK4R9P#F73
config/fortify
'username' => 'auth',
'email' => 'email',
Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use JoelButcher\Socialstream\HasConnectedAccounts;
use JoelButcher\Socialstream\SetsProfilePhotoFromUrl;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Jetstream\HasTeams;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto {
getProfilePhotoUrlAttribute as getPhotoUrl;
}
use HasTeams;
use HasConnectedAccounts;
use Notifiable;
use SetsProfilePhotoFromUrl;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
/**
* Get the URL to the user's profile photo.
*
* #return string
*/
public function getProfilePhotoUrlAttribute()
{
if (filter_var($this->profile_photo_path, FILTER_VALIDATE_URL)) {
return $this->profile_photo_path;
}
}
Users database
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->foreignId('current_connected_account_id')->nullable();
$table->foreignId('current_connected_post_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
}
}
action/fortify/UpdatesUserProfileInformation.php
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'alpha_dash:users', Rule::unique('users')->ignore($user->id)],
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:10024'],
])->validateWithBag('updateProfileInformation');
action/fortify/CreatesNewUsers.php
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users','alpha_dash:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return DB::transaction(function () use ($input) {
return tap(User::create([
'name' => $input['name'],
'email' => $input['email'],
'username' => $input['username'],
'password' => Hash::make($input['password']),
]), function (User $user) {
$this->createTeam($user);
});
});
provides/fortifyserviceprovider.php
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
return $user;
}
});
provides/jetstreamserviceprovider.php
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
return $user;
}
});
I have found the solution for all this,
Inside vendor/laravel/fortify/src/Actions/ConfirmPassword.php, there is a function __invoke which Confirm that the given password is valid for the given user.
In default, $username = config('fortify.username'); but my config('fortify.username') is set to auth that why it is not inside the database and return column not found
Is there a way to change this? cuz modifying the vendor is not a good solution.
You can do this in two ways and override the required items in Fortify
app()->singleton(ConfirmPassword::class, MyConfirmPassword::class);
or
// custom hook for confirming passwords
Fortify::confirmPasswordsUsing(function($user, $password) {
// your code!;
});
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 want to redirect to a previously accessed page right before accessing the registration page after a user has successfully registered themselves. I edited the registration controller as below although i get the following exception View [http:..127.0.0.1:8000.prices] not found. I cross checked my routes and everything is fine. Here is my register controller.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\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
*/
protected function validator(array $data)
{
return Validator::make($data, [
'fname' => ['required', 'string', 'max:255'],
'lname' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'phonenumber' => ['required', 'string', 'min:10', 'max:10'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'fname' => $data['fname'],
'lname' => $data['lname'],
'email' => $data['email'],
'phonenumber' => $data['phonenumber'],
'password' => Hash::make($data['password']),
]);
}
/**
* Show the application's registration form.
*
* #return \Illuminate\Http\Response
*/
public function showRegistrationForm()
{
if(session('link')) {
$myPath = session('link');
$registerPath = url('/register');
$previous = url()->previous();
if($previous = $registerPath) {
session(['link' => $myPath]);
}else{
session(['link' => $previous]);
}
}else{
session(['link' => url()->previous()]);
}
return view('auth.register');
}
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
}
I think the issue is most likely to be with the function:
protected function redirectTo()
{
if(session('link')){
return view(session('link'));
}
return view('/');
}
I tried replacing return view(session('link')); with return url()->previous(); but there was no luck. I am using laravel 7.
The issue was actually with adding view. Instead of return view(session('link')); use return (session('link')); Same applies to the return outside the if statement.
try to use redirect back
return Redirect::back();
do not forget to import redirect in controller
use Redirect;
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.