Home » Php » php – Laravel 5 Models Folder

php – Laravel 5 Models Folder

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a directory called models inside app/ where I place all my model classes. Now I want to change the directory where the following command outputs the generated classes

php artisan make:model SomeModel
How to&Answers:

You can’t and, if you’re hewing to Laravel’s version of the universe, you shouldn’t. Laravel 5 provides, and assumes, a PSR-4 naming convention for all its class files. This means models (and all classes) should be placed based on their full class name.

When you say

php artisan make:model SomeModel

You’re actually creating a model with the full name of App\SomeModel, so artisan creates the following file.

app/SomeModel.php

If you said

php artisan make:model 'Test\SomeModel'

you’d be creating a model with the full name App\Test\SomeModel, and Laravel would create the following file

app/Test/SomeModel.php

So, its your model’s full class name (namespace included) that determines where the class definition file is.

Answer:

I found it should be:

php artisan make:model ModelFolder\SomeModel

Answer:

If you want to create Models manually on specific folder. Example if you want to create model infointo folder Models. Create file named info.php inside folder Models that you created before. Here are you should write code like this in info.php

<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Info extends Model
{
    // your code
    protected $table = 'tb_users';
}

Of course you also can use Artisan command
php artisan make:model "Models\Info"

If you want to call that model Info you create a view

<?php
$users = App\Models\Info::all();

foreach ($users as $user) {
    echo $user->name;
}

It will display all name of users

Answer:

You could also look at www/yourfolder/database/php file created when the model was created.

Answer:

If you too lazy and don’t want to type the word Models every time, you can try this my https://github.com/bangnokia/laravel-models-folder

Answer:

Look into this using this tutorial on medium https://medium.com/@codingcave/organizing-your-laravel-models-6b327db182f9.
Its a better solution to extend the ModelMakeCommand so that instead of php artisan make:model 'Test\SomeModel' you will run php artisan make:model SomeModel and you’ll still get 'Test\SomeModel' namespace with SomeModel.php in 'Test' folder