Class 'Illuminate\Foundation\Auth\User' not found JWT Auth Laravel - php

I have written code for registration and login using JWT authentication. In this code registration function works fine but login function doesn't works. Login function prompts an error as Class 'Illuminate\Foundation\Auth\User' not found
My user model is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'users';
public $timestamps = false;
protected $primaryKey = 'user_name';
protected $fillable = ['user_name','password'];
}
My UserController is
class UsersController extends Controller
{
public function login()
{
$credentials = request()->only('user_name','password');
try{
$token = JWTAuth::attempt($credentials);
if($token){
return response()->json(['error'=>'invalid_credentials'],401);
}
}
catch(JWTException $e){
return response()->json(['error'=>'something went wrong'],500);
}
return response()->json(['token'=>$token],200);
}
public function register()
{
$user_name = request()->user_name;
$password = request()->password;
$user = User::create([
'user_name'=>$user_name,
'password'=>bcrypt($password)
]);
$token = JWTAuth::fromUser($user);
return response()->json(['token'=>$token],200);
}
}
The login function shows the error as
Class 'Illuminate\Foundation\Auth\User' not found

In your controller I guess you forgot to use your model "User" add it below the namespace declaration, Or it's a conflict with Illuminate\Foundation\Auth\User
use\App\User;
And you must run the following:
composer update
composer dump-autoload

The problem exists with my user model and I solved it
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{use Authenticatable, CanResetPassword;
//
protected $table = 'users';
public $timestamps = false;
protected $primaryKey = 'user_name';
protected $fillable = ['user_name','c_name','accessibility_level','password','role','contact_number','address'];
}

Related

Laravel 8 Auth Model Different

I want to create a model for my project but i don't know what's the different between the original MVC style and laravel default auth model
there's a directory different too. The original MVC was in Model folder, while the defaulth auth is in controller folder. I don't know why make a model inside the Controller folder
This is the code that's work ( laravel default auth model )
source : https://www.5balloons.info/changing-authentication-table-laravel/
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
protected $table = 'customusers';
protected $fillable = [
'name','username','email','passcode','active'
];
protected $hidden = [
'passcode',
];
}
while this code is not work with error Class 'App\Models\Authenticatable' not found
i can create a work around to use the class, but i need to understand why
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TestUser extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'testuser';
protected $fillable = [
'username','password',
];
protected $hidden = [
'password',
];
/*
public funtion getAuthPassword()
{
return $this-> passcode;
}
*/
}

Laravel class 'UserRole' not found

Hi i am trying to use a model for a test but i get Class 'App\UserRole' not found this is my controller where i am calling it
<?php
namespace App\Http\Controllers;
use App\UserRole;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function index()
{
$role = UserRole::get();
die(var_dump($role));
}
}
and this is my model
<?php
use \Illuminate\Database\Eloquent\Model as Eloquent;
class UserRole extends Eloquent
{
public $table = 'role';
public $primaryKey = 'id_role';
public $timestamps = false;
const ADMIN = 1;
const OPERATOR = 2;
const CUSTOMER = 3;
}
I dont know what im missing, i tried to do the same with User model and it works perfect, also my table is created and populated.
Add a namespace to your model
namespace App;
Should look like this:
<?php
namespace App;
use \Illuminate\Database\Eloquent\Model as Eloquent;
class UserRole extends Eloquent
{
public $table = 'role';
public $primaryKey = 'id_role';
public $timestamps = false;
const ADMIN = 1;
const OPERATOR = 2;
const CUSTOMER = 3;
}
You should add in your model
namespace App;

Laravel 6: Call to undefined method App\\User::createToken()

I'm trying to generate a token to authenticate users in my Controller the following way:
namespace App\Http\Controllers\API;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class AuthController extends Controller
{
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('myApp')->accessToken;
dd($success['token']);
}
}
Currently, I'm just trying to print out the token. And this is my User's model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
const USER_FIRST_NAME_FIELD = "first_name";
const USER_LAST_NAME_FIELD = "last_name";
const USER_PREFERRED_NAME_FIELD = "preferred_name";
const USER_EMAIL_FIELD = "email";
const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
const USER_PASSWORD_FIELD = "password";
const USER_REMEMBER_TOKEN_FIELD = "remember_token";
const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
const USER_ACTIVE_FIELD = "active";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
self::USER_FIRST_NAME_FIELD,
self::USER_LAST_NAME_FIELD,
self::USER_PREFERRED_NAME_FIELD,
self::USER_EMAIL_FIELD,
self::USER_PASSWORD_FIELD,
self::USER_RECEIVE_NEWSLETTER_FIELD,
self::USER_ACTIVE_FIELD,
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
self::USER_PASSWORD_FIELD,
self::USER_REMEMBER_TOKEN_FIELD
];
/**
* Automatically creates password hash when password is submitted
*
* #param string $password
* #return void
*/
public function setPasswordAttribute(string $password) : void
{
$this->attributes['password'] = Hash::make($password);
}
}
As you can see I'm using HasApiTokens, Notifiable traits and nonetheless I'm getting an error from my controller saying:
Call to undefined method App\User::createToken()
Passport is installed and configured correctly.
Here's something weird:
When registering an user (I'm using a separate controller and also using a service) a token is created successfully:
Here's my controller:
<?php
namespace App\Http\Controllers\API;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterUserRequest;
class UserController extends Controller
{
private $user;
public function __construct(UserService $user)
{
$this->user = $user;
}
public function store(RegisterUserRequest $request) : JsonResponse
{
// TODO: verify message on error
$user = $this->user->register($request->validated());
$token = $user->createToken('MyApp')->accessToken;
dd($token);
return response()->json(['status' => 201, 'user_id' => $user->id]);
}
}
Here's my service:
<?php
namespace App\Services;
use App\Models\User;
use App\Services\BaseServiceInterface;
class UserService implements BaseServiceInterface
{
public function register(array $formValues) : User
{
// 'terms and conditions' should not be saved into the db, hence it's removed
unset($formValues['terms_conditions']);
return User::create($formValues);
}
}
and here's my model again:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
const USER_FIRST_NAME_FIELD = "first_name";
const USER_LAST_NAME_FIELD = "last_name";
const USER_PREFERRED_NAME_FIELD = "preferred_name";
const USER_EMAIL_FIELD = "email";
const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
const USER_PASSWORD_FIELD = "password";
const USER_REMEMBER_TOKEN_FIELD = "remember_token";
const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
const USER_ACTIVE_FIELD = "active";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
self::USER_FIRST_NAME_FIELD,
self::USER_LAST_NAME_FIELD,
self::USER_PREFERRED_NAME_FIELD,
self::USER_EMAIL_FIELD,
self::USER_PASSWORD_FIELD,
self::USER_RECEIVE_NEWSLETTER_FIELD,
self::USER_ACTIVE_FIELD,
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
self::USER_PASSWORD_FIELD,
self::USER_REMEMBER_TOKEN_FIELD
];
As I told you, when creating a user the token is being generated correctly.
I'd say that Auth::user() is not calling my Model directly, but I don't know for sure that's what is happening.
Any idea why?
Thanks
Since your guard is returning the wrong User model, App\User, you should check your auth configuration, 'config/auth.php'. In the providers array adjust any provider, usually users, that is using the App\User model to App\Models\User instead.
'providers' => [
'users' => [
'driver' => 'eloquent',
// 'model' => App\User::class,
'model' => App\Models\User::class,
],
...
],
in my case, i missed to use Trait HasApiTokens
thats why laravel was unable to create tokens.
just open User.php
afetr name space include
use Laravel\Passport\HasApiTokens;
then inside class
use HasApiTokens
Pls note : I am using laravel 7.
So, this is not the right way to do it but it's working at the moment:
<?php
namespace App\Http\Controllers\API;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;
class AuthController extends BaseController
{
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$authenticated_user = \Auth::user();
$user = User::find($authenticated_user->id);
dd($user->createToken('myApp')->accessToken);
}
dd('here');
}
}
Now I'm seeing the token.
I wanna do it the right way so I still would appreciate if any one could help me.
Thanks
you can let the auth.basic middleware do the authentication for you, by calling it in the construct method:
public function __construct()
{
$this->middleware('auth.basic');
}
Then generate the access token for the currently authenticated user, and return the user information along with the access token:
public function login()
{
$Accesstoken = Auth::user()->createToken('Access Token')->accessToken;
return Response(['User' => Auth::user(), 'Access Token' => $Accesstoken]);
}
Now the Controller will look like this:
<?php
namespace App\Http\Controllers\API;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;
class AuthController extends BaseController
{
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth.basic');
}
public function login()
{
$Accesstoken = Auth::user()->createToken('Access Token')->accessToken;
return Response(['User' => Auth::user(), 'Access Token' => $Accesstoken]);
}
}
i have updated laravel 6 to 8 & i am using sanctum for API auth.
This works for me when i want to get token for API auth.
in User model
use Laravel\Sanctum\HasApiTokens;
and use the traits in function
use HasApiTokens
Model/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\Sanctum\HasApiTokens;
use Hash;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
'status'
];
/**
* 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',
];
public function setPasswordAttribute($input)
{
if ($input) {
$this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
}
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function scopeActive($query){
return $query->where('status', 'ACTIVE');
}
}

Argument 1 passed to Illuminate\Foundation\Testing\TestCase::actingAs()

I wanna try to make test, member who logged in can create a job, this is my test code.
/** #test */
public function member_can_create_a_job(){
$member = factory('App\Models\M_member')->create();
$this->actingAs($member);
$job = factory('App\Models\M_lowker')->make();
$this->post('/lowker/tambah-lowker', $job->toArray())->assertRedirect('/lowker/tambah-lowker');
}
This is my App\Models\M_member
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class M_member extends Model{
protected $table = "member";
public $timestamps = false;
protected $fillable = ["nama", "email", "password", "alamat", "tgl_lahir", "remember_token"];
public function jobs()
{
return $this->hasMany('App\Models\M_lowker');
}
public function comments()
{
return $this->hasMany('App\Models\M_komentar');
}
}
When I run, I get error in cmd like
this.
1) Tests\Feature\JPSTest::member_can_create_a_job TypeError: Argument 1 passed to Illuminate\Foundation\Testing\TestCase::actingAs() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\Models\M_member given, called in I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\tests\Feature\JPSTest.php on line 35
I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\InteractsWithAuthentication.php:16 I:\W 42 N\Home Work\Semester 5\Rekayasa Perangkat Lunak\Praktikum\jps\tests\Feature\JPSTest.php:35
ERRORS! Tests: 3, Assertions: 3, Errors: 1.
This error tells you that the model which you are using is not extending the Illuminate\Contracts\Auth\Authenticatable contract, which is necessary to use the actingAs method. If you have laravel's auth you can check the user model as an example of this . Which is something like:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
So, try extending your model to have this functionality.
or you can implement the Authenticatable contract on your model like this
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}
You can add first() when you create user
$user = factory('App\User')->create()->first();
This problem solved with modify my M_member model like this.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
class M_member extends Model implements Authenticatable{
use AuthenticableTrait;

Laravel 5.3 + Sentinel: BadMethodCallException in Builder.php line 2450

I'm trying to build my first Laravel application by following a few guides on the internet and I'm feeling I'm missing something obvious. Here is the code.
Error
BadMethodCallException in Builder.php line 2450: Call to undefined
method Illuminate\Database\Query\Builder::addresses()
User-Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Sentinel;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'email', 'password',
];
protected $hidden = [
'password',
'remember_token'
];
public function addresses()
{
return $this->hasMany('App\CustomerAddress');
}
}
CustomerAddress-model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerAddress extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
CustomerAddress-controller
<?php
namespace App\Http\Controllers;
use App\CustomerAddress;
use Illuminate\Http\Request;
class CustomerAddressController extends Controller
{
public function create(Request $request)
{
$address = new CustomerAddress();
$address->address = $request['address'];
$request->user()->addresses()->save($address);
}
}
Error appears after this piece of code:
$request->user()->addresses()->save($address);
Any ideas? Thanks and cheers
In .config/cartalyst.sentinel.php, change 'model' => 'Cartalyst\Sentinel\Users\EloquentUser' to 'model' => 'App\User' to use your user model with the addresses relation defined
In ./app/User change User extends Authenticatable to User extends \Cartalyst\Sentinel\Users\EloquentUser to extend sentinel's user to your app's User model
Finally, your controller code should now be
`$address = new CustomerAddress();
$address->address = $request->input('address');
$request->user()->addresses()->save($address);`
and everything should be peachy

Categories