My application in Laravel is presenting the following error after registering:
"BadMethodCallException
Call to undefined method Illuminate\Database\Query\Builder::getAuthIdentifierName()"
The error only appears after performing the authentication. If I clear my browser's cache, the error disappears and the application works normally.
I already saw other answers in StackOverflow and other sites, but none of them solved my problem. What could be happening?
Here is my User.php file:
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'cpf', 'name', 'lastname', 'email', 'password', 'auth', 'authy_id', 'api_token', 'block', 'blocked_at', 'session'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My code that does authentication is here:
public function auth($session, $gtag){
$user = User::where('session', $session)->first();
if(isset($user) && !empty($user)){
Auth::login($user);
//$time = decrypt($user->session);
$user->session = NULL;
$user->save();
setcookie('_ga', $gtag, (time() + 605800), '/', 'bmydomain.com');
setcookie('_gat_gtag_UA_115432851_1', '1', (time() + 605800), '/', 'mydomain.com');
return redirect($this->redirectTo);
}
else{
return redirect($this->redirectNotAuth);
}
}
On Kernel.php file use:
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
instead of
'auth' => \App\Http\Middleware\Authenticate::class,
Related
On laravel 9.19, laravel/passport": "^11.3 site
I added some more custom fields into users table, and making login method with code like :
public function login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return $this->sendResponse($success, 'User login successfully.');
}
else{
return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}
}
When I read logged user :
$user = Auth::user();
\Log::info($user);
$user has no my custom fields.
Just common app/Models/User.php :
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
How have I to define my custom fields ?
"laravel/framework": "^9.19",
"laravel/passport": "^11.3",
Thanks in advance!
I get a token it has 40 character random string like this...
1|z5F4SMYZRxLo8ScUYMmnExdYtQoJ8eaftQevF0Pa
And I want 240 character random string like this...
1|nvbqwunxjyxujtnqnqcxzhintxyswmsjdunbmuhkifbncgrucxchzirgkybtbcadrjjtjunroewmpidxwiobcvimbolzcjlmeddvusgqzmcakffyzqllbzihnvbqwunxjyxujtnqnqcxzhintxyswmsjdunbmuhkifbncgrucxchzirgkybtbcadrjjtjunroewmpidxwiobcvimbolzcjlmeddvusgqzmcakffyzqllbzih
Please help me for how to increase the length of the Laravel Sanctum Token
Open file: app/Models/User.php then
Check if this file is used Laravel\Sanctum\HasApiTokens trait
Override method: createToken like this:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\NewAccessToken;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Create a new personal access token for the user.
*
* #param string $name
* #param array $abilities
* #return \Laravel\Sanctum\NewAccessToken
*/
public function createToken(string $name, array $abilities = ['*'])
{
$token = $this->tokens()->create([
'name' => $name,
'token' => hash('sha256', $plainTextToken = Str::random(240)),
'abilities' => $abilities,
]);
return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
}
}
You can use:
$user->createToken('your name token')->plainTextToken;
I'm making a simple user authentication with laravel passport, I made an AuthController where I put login and register functions, whenever I try to login with the right email and password I get
{"message":"invalid user"}
its like the attempt() method always returning false, I am using laravel 8.
here is AuthController.php
<?php
namespace App\Http\Controllers;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function login(Request $request){
if(Auth::attempt($request->only('email', 'password'))){
$user=Auth::user();
return $user;
}
return response([
'message'=> 'invalid user'
], 401);
}
}
user model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'phone',
'skype',
'birthdate',
'address',
'postalcode',
'city',
'country',
'status',
'image',
'description',
'geo_lat',
'geo_lng'
];
/**
* 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',
];
}
AuthServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\Passport;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
I am using Laravel 7 and I am trying to verify my email I have followed all the steps mentioned in the documentation but I am still getting this error please me to resolve this error, Thanks
I added the user model code here
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password', 'permissions'
];
/**
* 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',
];
}
here is web.php
Auth::routes(['verify'=> true]);
Route::prefix('student')->middleware(['auth', 'verified'])->group(function () {
Route::get('dashboard', 'StudentController#dashboard');
});
The $request is sending a null value because you need to be logged in (authenticated) in order to get an instance of the $user
Make sure you have a middleware of auth on your route
Assigning Middleware To Routes:
Route::get('admin/profile', function () {
//
})->middleware('auth');
or Middleware Groups:
Route::group(['middleware' => ['auth']], function () {
Route::get('admin/profile', function(){
//your function here
});
});
Laravel Official Doc
only users logged could acheave the function hasVerifiedEmail() , because of that you get the response : Call to a member function hasVerifiedEmail() on null ,
to fix that issue you have to customise show function in VerificationController.php
public function show(Request $request)
{
//login user
if (auth()->user())
{
return $request->user()->hasVerifiedEmail()
? redirect($this->redirectPath())
: view('auth.verify');
}
//guest
else
{
return $request->user()
? redirect($this->redirectPath())
: redirect('/login');
}
}
I am playing around with Laravel Authentication.
On a freshly created Laravel app with Composer, I followed literally the instructions until this point (included)
https://laravel.com/docs/5.8/api-authentication#generating-tokens
When I register a new user, however, the api_token field is NULL.
What else do I need to do in order to start generating the api token when a user registers??
Create method in RegisterController:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(60),
]);
}
Migration (I called it Token) updating the users table:
class Token extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
}
App\User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* 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',
];
}
In your user model add 'api_token' to your fillables
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'api_token'
];
After creating migration , run the migrate Artisan command:
php artisan migrate
If you are using the Homestead virtual machine, you should run this command from within your virtual machine:
php artisan migrate --force