2

I am starting out with Laravel 5 and as first order of business I want to move all my models into a folder called Models.

But how can I access those without specifying the namespace like in the following?:

...

class UserRolesTableSeeder extends Seeder {

    public function run()
    {
        DB::table('user_roles')->delete();

        App\Models\UserRoles::create(['name' => 'CREATE_USER']);
    }

}

2 Answers 2

4

Go into your composer.json and add at the end of "autoload": "classmap" this line "app/models". This way you are telling laravel to autoload those clases. After that, run a composer update and it should work.

You can also create a service provider to access models without namespaces.

To create a service provider, here is what you have to do :

1) Create a file in your models directory and name it ModelsServiceProvider.php

2) Inside of it write this code

<?php
namespace App\Models;

use Illuminate\Support\ServiceProvider;

class ModelsServiceProvider extends ServiceProvider {

public function register()
{

    $this->app->booting(function()
    {
        $loader = \Illuminate\Foundation\AliasLoader::getInstance();
        $loader->alias('UserRoles', 'App\Models\UserRoles');

    });

}

3) Go into app/config/app.php and under providers array add this line 'App\Models\ModelsServiceProvider'

You can also add directly your aliases for classes under the aliases array inside app/config/app.php.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks, I remember something like that I did a while ago. Will accept in 1 minute! Another question, what if my app was split into modules? Would I just add all the paths for each modules models into the .json file?
Yes, if you want those classes to autoload !
Note, that after what i suggested in my comment, you have to run a composer update.
After adding "app/Models" to the json file its telling me that it can't find class UserRoles :(
I edited my comment ! To access it without namespaces, you have to define that service provider or add the aliases as i suggested there. Also, you should remove the App from namespace, everywhere you did that, including class definitions !
|
2

Alternatively, you can just load your models into the global namespace like you were doing before! It's a bit scary to go against the docs but so far we haven't had any issues with it.

To make sure your models are still loaded, you just need to add the reference to your composer.json:

(assumes your namespace is App\Models)

"autoload": {

    "classmap": [
        ...
        "app/Models/"
    ],
    ...
    "": [
        "app/Models/"
    ]

be sure to run composer dump-autoload

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.