skip to Main Content

I am trying to autoload models in laravel 9,

I want to use models in my blade files, but when i use a model i have to import it writing "use AppModelsUser", and after i can write "{{ User::all() }}", but if i dont import the model first it gives me this error: "Class "User" not found", so i want to write "{{ User::all() }}" without importing the model first (without writing this: "use AppModelsUser") in the blade file. How can i autoload them?

2

Answers


  1. Just like you do in all other Laravel versions, for example:

    $query = User::with("posts");
    $users = $query->get();
    

    Where User class needs to define what "posts" means, like:

    use AppPost;
    
    // ...
    
    public function posts()
    {
        return $this->hasMany(Post::class, 'user_id');
    }
    

    Note that above I query the "User" model, and auto-load any related "Post" model.

    Login or Signup to reply.
  2. You can manually alias things in config/app.php.

    'aliases' => Facade::defaultAliases()->merge([
        'User' => AppModelsUser::class,
        ... your other models here
    ])->toArray(),
    

    This will make User available without having to manually write AppModelsUser every time in the view and everywhere else.


    Just like you can write

    use DB;
    
    DB::table('users')->get();
    

    instead of

    use IlluminateSupportFacadesDB;
    
    DB::table('users')->get();
    

    You will be able to write use User instead of use AppModelsUser (though I do not recommend you to do this).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search