Error: Class '\ App \ User' not found in Laravel

0

Hello I was doing a project and then we decided to make a new driver and models, I'm new to laravel and I do not understand the flow perfectly, I in my routes I already point to my new controller and use the same views but not I know I may be failing this is my code:

login.blade.php


@extends('layouts.app')

@section('content')

<div class="container" class="wrap">
    <div class="container" id="conte" >
        <!-- Formulario -->
        <form method="POST" action="{{ route('login') }}">
            {{ csrf_field() }} 

            <!-- Ahora creado este metodo nos dira que le metodo login no existe y ahora lo creamos en en controlador -->
            <!-- <input type="hidden" name="token" value="{{ csrf_token() }}"> -->
            <div class="form-group {{ $errors->has('name') ? 'has-error' : '' }}">
                <input name="name" 
                       placeholder="USUARIO" 
                       id="input-form"
                       value="{{ old('name') }}"> 
                {!! $errors->first('name', '<span class="help-block mensajerror">:message</span>') !!}
            </div>


            <div class="form-group {{ $errors->has('password') ? 'has-error' : '' }}">
                <input type="password" 
                       name="password" 
                       placeholder="PASSWORD" 
                       id="input-form1" 
                       style="color:gray; background: #dee2e6; margin-top: -7px;">
                {!! $errors->first('password', '<span class="help-block mensajerror">:message</span>') !!}
            </div>


            <button type="submit" class="btn btn-primary" style="background-color: #007bff00; border-color: #007bff00; position: absolute;"></button>
        </form>

        <!-- Imagen -->
        <div class="container">
            <div class="row">
                <div class="col-12" style="text-align: center;">
                    <img src="./img/logo.png" id="img">
                </div>
            </div>
        </div>

        <!-- Recuperar Contraseña -->
        <div class="container" id="forgot">
            <a href="" id="text-forgot">RECUPERA TU CONTRASEÑA</a>
        </div>

    </div>
</div>
@endsection

My route file web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', 'AdminController@showLoginForm'); // Podemos dejarle el middleware aca ->middleware('guest') o en el controlador

//Obtenemos la pagina dashboard, lacreamos con el controlador DashboardController , llamamos el metodo index y le damos el nombre dashboard
Route::get('dashboard', 'DashboardController@index')->name('dashboard');

Route::post('login', 'AdminController@login')->name('login'); 
//post es el metodo usado, enviamos la url login y el controlador Admincontroller en el metodo @login  y el nombre de la ruta sera login tambien

//esto hara que al acceder nos dira que expiro por inactividad esto quiere decir que no le hemos enviamos el csrf (desde el formulario)


Route::post('logout', 'Auth\LoginController@logout')->name('logout'); 

My controller

<?php

namespace App\Http\Controllers;

use App\Admin;
use Illuminate\Http\Request;
use Auth;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{

    public function __contruct() {
        $this->middleware('guest', ['only' => 'showLoginForm']); // Para que solo los no autenticados vean esta pagina
    }

    public function showLoginForm() {
        return view('auth.login'); //Retornamos la vista login ubicada en la carpeta auth
    }


    public function login() {

        $credentials = $this->validate(request(), [

            //Reglas de validacion
            $this->username() => 'required|string',
            'password' => 'required|string'

        ]);

        if(Auth::attempt($credentials)) {    // Auth::attempt($credentials ,Devuelve un boolean . No olvidar importar auth(use auth)
            return redirect()->route('dashboard');
        }
        // Cargamos los input para que recuerde el valor al momento de retornar a la pagina por error de datos withErrors (nombre) mensaje
        // En caso de no pasar autentificacion devuelve error 
        //cargamos el mensaje de error de resources/lang/en/auth .llave en este caso failed
        return back()->withErrors([$this->username() => trans('auth.failed')]) 
                     ->withInput(request([$this->username()]));


    }

    public function logout() {
        Auth::logout();
        return redirect('/');
    }

// Como queremos es loguearnos con el name solo debemos cambiar el email por name pero como hay varias referencias a email creamos un metodo que nos devuelva el campo con el queremos autenticar
    public function username() {
        return 'name';
    }



    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Admin  $admin
     * @return \Illuminate\Http\Response
     */
    public function show(Admin $admin)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Admin  $admin
     * @return \Illuminate\Http\Response
     */
    public function edit(Admin $admin)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Admin  $admin
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Admin $admin)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Admin  $admin
     * @return \Illuminate\Http\Response
     */
    public function destroy(Admin $admin)
    {
        //
    }
}

index method of the dashboard

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class DashboardController extends Controller {

    public function __construct() {
        // Para que solo deje pasar a los usuarios autenticados
        $this->middleware('auth');
    }

     public function index() {
        return view('dashboard');
     }
}

?>

Detail of the error:

  

C: \ xampp \ htdocs \ pikum.mapu \ vendor \ laravel \ framework \ src \ Illuminate \ Auth \ EloquentUserProvider.php

         * @param  array  $credentials
         * @return bool
         */
        public function validateCredentials(UserContract $user, array $credentials)
        {
            $plain = $credentials['password'];

            return $this->hasher->check($plain, $user->getAuthPassword());
        }

        /**
         * Create a new instance of the model.
         *
         * @return \Illuminate\Database\Eloquent\Model
         */
        public function createModel()
        {
            $class = '\'.ltrim($this->model, '\');

            return new $class;
        }

        /**
         * Gets the hasher implementation.
         *
         * @return \Illuminate\Contracts\Hashing\Hasher
         */
        public function getHasher()
        {
            return $this->hasher;
        }

This is the model (Admin.php) that I should use but I'm not sure what I should bring:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    //
}

Part of the folder structure just in case

The error gives me after I logueo when I should show my dashboard view

HERE THE PROJECT

    
asked by Naoto Amari 18.02.2018 в 17:57
source

1 answer

3

The error is common when you want to authenticate or validate access controls with middleware , by default the model User is used, this is specified in the file config/auth.php in the section providers , in the property model the model to be used in that case is defined by default App\User::class . If you want to change to another model you should modify there and place the one you want in this case App\Admin::class .

This will solve the error but what you are trying to do is create login with different models for which you must make some modifications. For this case it would be better to create a new guard in the file auth.php in the section guards would have and in the section providers

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    // Nuevo Guard
    'admins' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
],


'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    //Nuevo Provider
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
],

And your controller would be otherwise, using the traits provided by laravel , AuthenticatesUsers , your controller could be as follows.

<?php 

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{

    //trait
    use AuthenticatesUsers;

    //La vista de login
    protected $loginView ="auth.login";

    // El nombre del guard que se creo para administradores
    protected $guard ="admins"


    // Este método funcionará para hacer la redirección después de login
    protected function authenticated()
    {
        return redirect()->route('dashboard');
    }

}

In addition, your model as an important part should extend from Authenticatable

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
    //
}
    
answered by 18.02.2018 / 18:43
source