Error class app models user not found

I have laravel app. It works locally, using php artisan serve command. After deployment to remote server it does not work. Every artisan command returns: [SymfonyComponentDebugException

I have laravel app.

It works locally, using php artisan serve command.

After deployment to remote server it does not work.

Every artisan command returns:

 [SymfonyComponentDebugExceptionFatalThrowableError]  
 Class 'AppModelsUser' not found      

Excerpt from AppModelsUser.php (case-sensitive).

<?
namespace AppModels;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;

class User extends Authenticatable {
// code here
}

composer dump-autoload does not fix it.

.gitignore

/vendor
.env
/public/css/
/public/js/
/public/img/
/public/fonts/
/node_modules/

composer.json

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.3.*",
    "caouecs/laravel-lang": "~3.0"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.0",
    "symfony/css-selector": "3.1.*",
    "symfony/dom-crawler": "3.1.*"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\": "app/",
        "Seeds\": "database/seeds/"
    },
    "files": [
        "app/Http/Helpers.php"
    ]
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
},
"scripts": {
    "post-root-package-install": [
        "php -r "file_exists('.env') || copy('.env.example', '.env');""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\Foundation\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\Foundation\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist"
}

}

Local system: arch linux with php 7.0
Remote system: debian jessie with php 7.0

Hi, I have recently started learning Laravel-5 and i am developing rest web service. To make api secure i am using JWT(«tymon/jwt-auth»: «0.5.*»). I am facing the same issue as stated above.
I have moved the user class from «AppUser» to «AppModelsUser» and i have added following code in jwt.php

‘user’ => ‘AppModelsUser’, // code in jwt.php

Inside my Controller Action i have written following code

public function signIn(SignInRequestValidationRules $request)
{

$credentials = $request->only(’email’, ‘password’);
try {
if(! $token = JWTAuth::attempt($credentials)) {
return response()->json([‘error’ => ‘invalid_credentials’], 401);
}
} catch (JWTException $e) {
return response()->json([‘error’ => ‘could_not_create_token’], 500);
}
return response()->json(compact(‘token’));
}

Now whenever i am accessing signIn action using postman i am getting the following exception message.
«Class ‘AppUser’ not found At Line 130 in E:xampphtdocslaravel-rest-servicevendorlaravelframeworksrcIlluminateAuthEloquentUserProvider.php».

If i change the value in Auth.php as shown below

‘providers’ => [
‘users’ => [
‘driver’ => ‘eloquent’,
‘model’ => AppModelsUser::class,
],
// …
],

After changing model value to AppModelsUser::class i am facing another exception which is as follows.

«Argument 1 passed to IlluminateAuthEloquentUserProvider::validateCredentials() must be an instance of IlluminateContractsAuthAuthenticatable, instance of AppModelsUser given, called in E:xampphtdocslaravel-rest-servicevendorlaravelframeworksrcIlluminateAuthSessionGuard.php on line 385 and defined At 114 in E:xampphtdocslaravel-rest-servicevendorlaravelframeworksrcIlluminateAuthEloquentUserProvider.php»

Kindly provide your valuable inputs.

Вспоминаю YII2

Модель

namespace appmodels;

use Yii;
use yiibaseModel;
//use yiidbActiveRecord;

class LoginForm extends Model
{
...
    public function validatePassword($attribute,$params){
        $user = User::findOne([
          'email'=>$this->email
        ]);

        if(!$user || ($user->password != $this->password)){
            $this->addError($attribute, 'ошибка');
        }
    }
...
}

контроллер

namespace appcontrollers;

use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use appmodelsLoginForm;
use appmodelsRegistrationForm;

class BaseController  extends Controller{
...
 public function actionLogin()
  {
    if (!Yii::$app->user->isGuest) {
      return $this->goHome();
    }

    $login = new LoginForm();
    if ( Yii::$app->request->post('LoginForm')) { //$login->load(Yii::$app->request->post('LoginForm') && $login->login()
      $login->attributes = Yii::$app->request->post('LoginForm');
      if($login->validate()){
        var_dump("Всё тип топ");
        die();
      }
      //return $this->goBack();
    }

    return $this->render('login', [
      'model' => $login,
    ]);
  }
...
  }

Гуглю но пока чего-то не понял
ошибка — >
$user = User::findOne

Эх.. нашёл ошибку, надо было в LoginForm.php класс переписать.
User в Users

Код: Выделить всё

2015-04-29 07:40:35 [192.168.56.1][-][neijgqtsahfvop785qpkemo1v2][error][yiibaseErrorException:1] exception 'yiibaseErrorException' with message 'Class 'appmodelsUser' not found' in /var/www/tnved/models/LoginForm.php:74
Stack trace:
#0 /var/www/tnved/vendor/yiisoft/yii2/validators/InlineValidator.php(69): appmodelsLoginForm->validatePassword()
#1 /var/www/tnved/vendor/yiisoft/yii2/validators/InlineValidator.php(69): ::call_user_func:{/var/www/tnved/vendor/yiisoft/yii2/validators/InlineValidator.php:69}()
#2 /var/www/tnved/vendor/yiisoft/yii2/validators/Validator.php(238): yiivalidatorsInlineValidator->validateAttribute()
#3 /var/www/tnved/vendor/yiisoft/yii2/base/Model.php(333): yiivalidatorsValidator->validateAttributes()
#4 /var/www/tnved/models/LoginForm.php(59): yiibaseModel->validate()
#5 /var/www/tnved/controllers/SiteController.php(62): appmodelsLoginForm->login()
#6 /var/www/tnved/vendor/yiisoft/yii2/base/InlineAction.php(55): appcontrollersSiteController->actionLogin()
#7 /var/www/tnved/vendor/yiisoft/yii2/base/InlineAction.php(55): ::call_user_func_array:{/var/www/tnved/vendor/yiisoft/yii2/base/InlineAction.php:55}()
#8 /var/www/tnved/vendor/yiisoft/yii2/base/Controller.php(151): yiibaseInlineAction->runWithParams()
#9 /var/www/tnved/vendor/yiisoft/yii2/base/Module.php(455): yiibaseController->runAction()
#10 /var/www/tnved/vendor/yiisoft/yii2/web/Application.php(83): yiibaseModule->runAction()
#11 /var/www/tnved/vendor/yiisoft/yii2/base/Application.php(375): yiiwebApplication->handleRequest()
#12 /var/www/tnved/web/index.php(12): yiibaseApplication->run()
#13 {main}
2015-04-29 07:40:35 [192.168.56.1][-][neijgqtsahfvop785qpkemo1v2][info][application] $_POST = [
    '_csrf' => 'YXFTWmVPemNSQxQoKhcMCiRGACMOGwBUNT4FbBUeKxszJCENJGINUw=='
    'LoginForm' => [
        'username' => 'demo'
        'password' => '    2f197c497b6220c0d34fb52987e73389'
        'rememberMe' => '1'
    ]
    'login-button' => 'Отправить'
]

$_COOKIE = [
    '_csrf' => '04df536c743656e3679996062c42dc310bf7b0fcc96b5e639756188f9e159ee0a:2:{i:0;s:5:"_csrf";i:1;s:32:"32GrOXviE7SykTz7TOV6pQQxRUrWA-w0";}'
    'PHPSESSID' => 'neijgqtsahfvop785qpkemo1v2'
]

$_SESSION = [
    '__flash' => []
]

$_SERVER = [
    'HTTP_USER_AGENT' => 'Opera/9.80 (Windows NT 6.1; WOW64) Presto/2.12.388 Version/12.17'
    'HTTP_HOST' => 'www.tnved.test1.ru'
    'HTTP_ACCEPT' => 'text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1'
    'HTTP_ACCEPT_LANGUAGE' => 'ru-RU,zh-cn;q=0.9,ru;q=0.8,en;q=0.7'
    'HTTP_ACCEPT_ENCODING' => 'gzip, deflate'
    'HTTP_REFERER' => 'http://www.tnved.test1.ru/index.php/site/login'
    'HTTP_COOKIE' => '_csrf=04df536c743656e3679996062c42dc310bf7b0fcc96b5e639756188f9e159ee0a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%2232GrOXviE7SykTz7TOV6pQQxRUrWA-w0%22%3B%7D; PHPSESSID=neijgqtsahfvop785qpkemo1v2'
    'HTTP_CACHE_CONTROL' => 'no-cache'
    'HTTP_CONNECTION' => 'Keep-Alive'
    'CONTENT_LENGTH' => '279'
    'CONTENT_TYPE' => 'application/x-www-form-urlencoded'
    'PATH' => '/usr/local/bin:/usr/bin:/bin'
    'SERVER_SIGNATURE' => ''
    'SERVER_SOFTWARE' => 'Apache/2.2.22 (Debian)'
    'SERVER_NAME' => 'www.tnved.test1.ru'
    'SERVER_ADDR' => '192.168.56.101'
    'SERVER_PORT' => '80'
    'REMOTE_ADDR' => '192.168.56.1'
    'DOCUMENT_ROOT' => '/var/www/tnved/web'
    'SERVER_ADMIN' => '[no address given]'
    'SCRIPT_FILENAME' => '/var/www/tnved/web/index.php'
    'REMOTE_PORT' => '45878'
    'GATEWAY_INTERFACE' => 'CGI/1.1'
    'SERVER_PROTOCOL' => 'HTTP/1.1'
    'REQUEST_METHOD' => 'POST'
    'QUERY_STRING' => ''
    'REQUEST_URI' => '/index.php/site/login'
    'SCRIPT_NAME' => '/index.php'
    'PATH_INFO' => '/site/login'
    'PATH_TRANSLATED' => 'redirect:/index.php/login'
    'PHP_SELF' => '/index.php/site/login'
    'REQUEST_TIME_FLOAT' => 1430293235.612
    'REQUEST_TIME' => 1430293235
]
 

Users.php

Код: Выделить всё

<?php

namespace appmodels;

use Yii;

use yiibaseNotSupportedException;
use yiidbActiveRecord;
use yiihelpersSecurity;
use yiiwebIdentityInterface;
/**
 * This is the model class for table "users".
 *
 * @property integer $id
 * @property integer $owner_id
 * @property integer $default_c_id
 * @property integer $public
 * @property string $login
 * @property string $password
 * @property string $role
 * @property string $username
 * @property string $email
 * @property string $PersonSurname
 * @property string $PersonMiddleName
 * @property string $sex
 * @property string $dateOfBirth
 * @property string $Phone
 * @property integer $tarif
 * @property string $services
 * @property integer $checked
 * @property integer $checkMail
 * @property integer $tng
 * @property string $profile
 */
class Users extends yiidbActiveRecord  implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['owner_id', 'default_c_id', 'login', 'password', 'username', 'email', 'tarif', 'profile'], 'required'],
            [['owner_id', 'default_c_id', 'public', 'tarif', 'checked', 'checkMail', 'tng'], 'integer'],
            [['role', 'sex'], 'string'],
            [['dateOfBirth'], 'safe'],
            [['login'], 'string', 'max' => 63],
            [['password'], 'string', 'max' => 32],
            [['username', 'email'], 'string', 'max' => 255],
            [['PersonSurname', 'PersonMiddleName'], 'string', 'max' => 150],
            [['Phone'], 'string', 'max' => 24],
            [['services'], 'string', 'max' => 18],
            [['profile'], 'string', 'max' => 250],
            [['login'], 'unique'],
            [['email'], 'unique'],
            ['role', 'default', 'value' => 'user'], // default role user(create users)
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'owner_id' => 'Owner ID',
            'default_c_id' => 'Default C ID',
            'public' => 'Public',
            'login' => 'Login',
            'password' => 'Password',
            'role' => 'Role',
            'username' => 'Username',
            'email' => 'Email',
            'PersonSurname' => 'Person Surname',
            'PersonMiddleName' => 'Person Middle Name',
            'sex' => 'Sex',
            'dateOfBirth' => 'Date Of Birth',
            'Phone' => 'Phone',
            'tarif' => 'Tarif',
            'services' => 'Services',
            'checked' => 'Checked',
            'checkMail' => 'Check Mail',
            'tng' => 'Tng',
            'profile' => 'Profile',
        ];
    }
    
    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
        /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
/* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
          return static::findOne(['access_token' => $token]);
    }
 
/* removed
    public static function findIdentityByAccessToken($token)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
*/
    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['login' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param  string      $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        if ($timestamp + $expire < time()) {
            // token expired
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        //! BUG, need true encode
        return $this->password === $password;
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Security::generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Security::generateRandomKey();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
    /** EXTENSION MOVIE **/
}

 

LoginForm.php

Код: Выделить всё

<?php

namespace appmodels;

use Yii;
use yiibaseModel;

/**
 * LoginForm is the model behind the login form.
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $rememberMe = true;

    private $_user = false;


    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }

        return $this->_user;
    }
}

74
Stack

Hey guys,

I seem to be getting an issue where if I try and run my project locally it works fine but I can’t get composer install to work at all on my server.

My localhost is Mac and the server is Linux I am using Nginx to serve the actual project. This project has been working fine on the server and I just rebuilt it yesterday and suddenly it doesn’t want to work anymore.

Upon running composer install I get the following error:

> @php artisan package:discover --ansi

   Error 

  Class 'AppUser' not found

  at app/Providers/AppServiceProvider.php:21
     17▕      */
     18▕     public function boot()
     19▕     {
     20▕         Item::observe(ItemObserver::class);
  ➜  21▕         User::observe(UserObserver::class);
     22▕     }
     23▕ 
     24▕     /**
     25▕      * Register any application services.

      +7 vendor frames 
  8   [internal]:0
      IlluminateFoundationApplication::IlluminateFoundation{closure}(Object(AppProvidersAppServiceProvider))

      +5 vendor frames 
  14  artisan:37
      IlluminateFoundationConsoleKernel::handle(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput))
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 1

My composer.json file (looking pretty basic, don’t judge!)

 "autoload": {
        "psr-4": {
            "App\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },

My autoload_classmap.php mention of User.php

'App\User' => $baseDir . '/app/Models/User.php', 

As you can see User.php lives in App/Models

Things I have tried:

  • Clearing all caches, including bootstrap (this didn’t work)

  • Checking for case sensitivity based issues (couldn’t find any)

  • People suggested that it could be a PHP version issue but the php on my server is 7.3 which is compatible with my project

URLS I have looked at:

  • I did write up an extensive list but seems my post got removed instantly because of this… but trust me my Google search page is nothing but purple!

Anyways if someone could point out anything else I might have missed please do so it would be much appreciated. And if you require further information on anything please let me know.

Note: I’m a C# dev just playing with this for fun wanted to learn it so please don’t be mean if I have overlooked something really obvious!

Error - Class "AppHttpControllersUser" not found - Laravel

Hi all,

Today, I will let you know example of laravel user class not found. I explained simply about laravel class ‘app user’ not found.

You can solve ‘Class «AppHttpControllersUser» not found’ issue in laravel 6, laravel 7, laravel 8 and laravel 9 version.

Error Class ‘AppHttpControllersUser’ not found occurs when you forget to include the user model in your controller.

So, let’s start following example:

Error:

It was my fault there, If you are using User class in controller then you need to use model namespace there in Controller, Middleware, or blade file then you must have used model namespace on top.

so let’s see bellow solution and example code here:

Solution:

Then after add «use AppModelsUser;» on top of controller, middleware, command, event or blade files. Let’s see bellow:

use AppModelsUser;

Example:

You can see controller file code, how to use it.

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppModelsUser;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return IlluminateHttpResponse

*/

public function index(Request $request)

{

$user = User::find(1);

return view('users');

}

}

I hope it can help you…

#Laravel

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

1 answer to this question.

Hello @kartik

Go to config/auth.php and change AppUser:class to AppModelsUser::class.

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => AppModelsUser::class,
    ],

Also change the namespace of User.php model

namespace AppModels;






answered

Apr 3, 2020


by
Niroj


• 82,840 points



Related Questions In Laravel

  • All categories

  • ChatGPT
    (2)

  • Apache Kafka
    (84)

  • Apache Spark
    (596)

  • Azure
    (131)

  • Big Data Hadoop
    (1,907)

  • Blockchain
    (1,673)

  • C#
    (141)

  • C++
    (271)

  • Career Counselling
    (1,060)

  • Cloud Computing
    (3,446)

  • Cyber Security & Ethical Hacking
    (147)

  • Data Analytics
    (1,266)

  • Database
    (855)

  • Data Science
    (75)

  • DevOps & Agile
    (3,575)

  • Digital Marketing
    (111)

  • Events & Trending Topics
    (28)

  • IoT (Internet of Things)
    (387)

  • Java
    (1,247)

  • Kotlin
    (8)

  • Linux Administration
    (389)

  • Machine Learning
    (337)

  • MicroStrategy
    (6)

  • PMP
    (423)

  • Power BI
    (516)

  • Python
    (3,188)

  • RPA
    (650)

  • SalesForce
    (92)

  • Selenium
    (1,569)

  • Software Testing
    (56)

  • Tableau
    (608)

  • Talend
    (73)

  • TypeSript
    (124)

  • Web Development
    (3,002)

  • Ask us Anything!
    (66)

  • Others
    (1,929)

  • Mobile Development
    (263)

Subscribe to our Newsletter, and get personalized recommendations.

Already have an account? Sign in.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error cb never called
  • Error caused by file vmdk при копировании
  • Error cin was not declared in this scope
  • Error catch without try
  • Error cat пет симулятор

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии