How to generate "make:model -a" with directory for seeders and controller and migrate name? - factory

How to generate "make:model -a" with directory for seeders and controller and migrate name?
Laravel Framework 8.44.0
I am generating a model php artisan make:model Blog/MyCategory -a and expect to see the following structure:
Controllers/Blog/MyCategoryController.php
Models/Blog/MyCategory.php
factories/Blog/MyCategory.php
mifrations/2021_06_01_042639_create_blog_my_categories_table.php
seeders/Blog/MyCategorySeeder.php
Execute the command php artisan make:model Blog/Category -a
Model created successfully.
Factory created successfully.
Created Migration: 2021_06_01_044253_create_my_categories_table
Seeder created successfully.
Controller created successfully.
but it creates
Controllers/MyCategoryController.php (NO)
Models/Blog/MyCategory.php (YES)
factories/Blog/MyCategory.php (YES)
mifrations/2021_06_01_042639_create_my_categories_table.php (NO)
seeders/MyCategorySeeder.php (NO)
This way I cannot generate two MyCategory.
Execute the command php artisan make:model Shop/MyCategory -a
Model created successfully.
Factory created successfully.
InvalidArgumentException
A CreateMyCategoriesTable class already exists.
at vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationCreator.php:102
Remove the
model Shop/MyCategory.php,
factory Shop/MyCategoryFactory.php
migration file 2021_06_01_044253_create_my_categories_table.php
Now let's create the correct migration file
php artisan make:migration CreateBlogMyCategoryTable
Again execute the command php artisan make:model Shop/MyCategory -a
Model created successfully.
Factory created successfully.
Created Migration: 2021_06_01_050039_create_my_categories_table
Seeder already exists!
Controller already exists!
It again creates a 2021_06_01_050039_create_my_categories_table file and does not take into account the model in the Shop directory
Remove generated files again:
model Shop/MyCategory.php
factory Shop/MyCategoryFactory.php
migration file 2021_06_01_050039_create_my_categories_table.php
controller MyCategoryController.php
Now let's create the correct migration and controllers:
php artisan make:migration CreateShopMyCategoryTable
php artisan make:controller Blog/MyCategoryController
php artisan make:controller Shop/MyCategoryController
Total
Thus, we see that the "-а" option is not suitable in this case. You need to create models, controllers and migrations separately.
php artisan make:controller Blog/MyCategoryController -r
php artisan make:controller Shop/MyCategoryController -r
php artisan make:migration CreateBlogMyCategoryTable
php artisan make:migration CreateShopMyCategoryTable
Model with factory
php artisan make:model Blog/MyCategory -f
php artisan make:model Shop/MyCategory -f
This command also makes the correct Factory
php artisan make:factory Blog\\MyCategoryFactory --model=Blog\\MyCategory
<?php
namespace Database\Factories\Blog;
use App\Models\Blog\MyCategory;
use Illuminate\Database\Eloquent\Factories\Factory;
class MyCategoryFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = MyCategory::class;
// ....
}
The migration files, models, and controllers as we need in the appropriate directories.
php artisan migrate
Migration table created successfully.
...
Migrating: 2021_06_01_055036_create_blog_my_category_table
Migrated: 2021_06_01_055036_create_blog_my_category_table (36.26ms)
Migrating: 2021_06_01_055541_create_shop_my_category_table
Migrated: 2021_06_01_055541_create_shop_my_category_table (39.16ms)
As I understand it, the required structure will still have to be done by separate commands.
But then another problem appeared: I do not understand how to use now factory()->create()
Route::get('/', function () {
\App\Models\Blog\MyCategory::factory(1)->create();
return view('welcome');
});
Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:59:52, 2021-06-01 06:59:52))
or tinker
php artisan tinker
Psy Shell v0.10.8 (PHP 7.4.18 — cli) by Justin Hileman
>>> MyCategory::factory()->create()
PHP Error: Class 'MyCategory' not found in Psy Shell code on line 1
>>> Blog\MyCategory::factory()->create()
PHP Error: Class 'Blog\MyCategory' not found in Psy Shell code on line 1
>>> \Blog\MyCategory::factory()->create()
PHP Error: Class 'Blog\MyCategory' not found in Psy Shell code on line 1
>>> App\Models\Blog\MyCategory::factory()->create()
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:48:26, 2021-06-01 06:48:26))'
>>> \App\Models\Blog\MyCategory::factory()->create()
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:48:29, 2021-06-01 06:48:29))'
How to make such a structure work?

Sometimes it is necessary to clear the cache, this command worked in my project:
composer dump-autoload
Good luck!

use php artisan make:model ModelName -mcr -a
it will create all that you need. migration, seeder, factory, controller and model

Related

Adding column using make migration command error

I'm trying to add an icon_path column to an existing table called tbl_device
by using php artisan make:migration add_icon_path_to_tbl_device_table --table=tbl_device
and after running php artisan migrate, it gives me this error.
PHP Fatal error: Cannot declare class CreateFailedJobsTable, because the name is already in use in ...path\database\migrations\<date>_create_failed_jobs_table.php
Cannot declare class CreateFailedJobsTable, because the name is already in use
I've also tried manually adding the icon_path column to the create_tbl_device_table.php migration and after running php artisan migrate it says Nothing to migrate.
I think I followed all the instructions.. any idea where I went wrong?
Call artisan migrate command only for your specific migration using:
php artisan migrate --path=/database/migrations/my_migrations
And see if it works.

Artisan 'Nothing to rollback' when there is a table already created

I wanted to make a migration using php artisan migrate but I got an error:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users' already exists
So naturally I wanted to drop my tables using php artisan migrate:rollback, but I got:
Nothing to rollback.
What the heck? It said just earlier that the users table was already created. What should I do? I can delete the table with phpmyadmin but I want to learn how to use artisan.
Thank you for your help.
Failing an answer to how to delete the tables with artisan when there is this problem, I will tell you how to avoid this problem in the first place. Ultimately I just deleted the tables using phpmyadmin.
I watched a tutorial on Laravel and I saw that in order to avoid the error:
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes
I had to add use Illuminate\Support\Facades\Schema; in AppServiceProvider.php and Schema::defaultStringLength(191); in the boot() function. But I thought that I could put any number in defaultStringLength(...) so I put 255, and the migration didn't work.
Do as it is told in the tutorials, write Schema::defaultStringLength(191);. Then, you can execute your migration using php artisan migrate and it should work properly.
In my case after defining Schema::defaultStringLength(191); in the boot() method didn't solved. Because the migrations table in the database is empty.
So the solution is open up the tinker from the composer
$ php artisan tinker
>>> Schema::drop('users')
>>> Schema::drop('password_resets')
>>> Schema::drop('orders')
>>> exit
php artisan migrate
Here is the result of the above commands executed
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
In Connection.php line 647:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
already exists (SQL: create table users (id int unsigned not
null auto_incr ement primary key, name varchar(255) not null,
email varchar(255) not n ull, password varchar(255) not null,
remember_token varchar(100) null, created_at timestamp null,
updated_at timestamp null) default character set utf8mb4
collate utf8mb4_unicode_ci)
In Connection.php line 449:
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'users'
alre ady exists
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate:rollback
Nothing to rollback.
nishanth#localhost:~/Desktop/html/hutch$ php artisan tinker
Psy Shell v0.8.17 (PHP 7.1.20-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> Schema::drop('users')
=> null
>>> Schema::drop('password_resets')
=> null
>>> Schema::drop('orders')
=> null
>>> exit
Exit: Goodbye.
nishanth#localhost:~/Desktop/html/hutch$ php artisan migrate
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrating: 2018_08_18_071213_create_orders_table
Migrated: 2018_08_18_071213_create_orders_table
nishanth#localhost:~/Desktop/html/hutch$
Also define the method down(), if it doesn't exist.
Otherwise, it'll show
SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'XYZ.ABC' (SQL: drop table ABC)
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('ABC');
}
SOLUTION:
>> php artisan migrate:fresh
It will drop all tables and recreates all the migrations.
Add use Illuminate\Support\Facades\Schema; in AppServiceProvider.php and Schema::defaultStringLength(191); in the boot() function
Run php artisan migrate:fresh
Run php artisan migrate again
Solved!
php artisan db:wipe
It is a quick way to drop all the tables, their types and views if you’re using Laravel 6.x
Full description:
$ php artisan db:wipe {--database=} {--drop-views} {--drop-types} {--force}
database - The database connection to use
drop-views - Drop all tables and views
drop-types - Drop all tables and types (Postgres only)
force - Force the operation to run when in production

Laravel - create model, controller and migration in single artisan command

I can create a model and resource controller (binded to model) with the following command
php artisan make:controller TodoController --resource --model=Todo
I want to also create a migration with the above command, is it possible?
You can do it if you start from the model
php artisan make:model Todo -mcr
if you run php artisan make:model --help you can see all the available options
-m, --migration Create a new migration file for the model.
-c, --controller Create a new controller for the model.
-r, --resource Indicates if the generated controller should be a resource controller
Update
As mentioned in the comments by #arun in newer versions of laravel > 5.6 it is possible to run following command:
php artisan make:model Todo -a
-a, --all Generate a migration, factory, and resource
controller for the model
Updated
Laravel 6 or Later
Through the model
To Generate a migration, seeder, factory and resource controller for the model
php artisan make:model Todo -a
Or
php artisan make:model Todo -all
Other Options
-c, --controller Create a new controller for the model
-f, --factory Create a new factory for the model
--force Create the class even if the model already exists
-m, --migration Create a new migration file for the model
-s, --seed Create a new seeder file for the model
-p, --pivot Indicates if the generated model should be a custom intermediate table model
-r, --resource Indicates if the generated controller should be a resource controller
For More Help
php artisan make:model Todo -help
Hope Newbies will get help.
You can do it with the following command:
php artisan make:model post -mcr
Brief :
-m, to create migration
-c to create controller
-r to specify the controller has resource
You can make model + migration + controller, all in one line, using this command:
php artisan make:model --migration --controller test
Short version: php artisan make:model -mc test
Output :-
Model created successfully.
Created Migration:2018_03_10_002331_create_tests_table
Controller created successfully.
If you need to perform all CRUD operations in the controller then use this command:
php artisan make:model --migration --controller test --resource
Short version: php artisan make:model -mc test --resource
php artisan make:model PurchaseRequest -crm
The Result is
Model created successfully.
Created Migration: 2018_11_11_011541_create_purchase_requests_table
Controller created successfully.
Just use -crm instead of -mcr
php artisan make:model Author -cfmsr
-c, --controller Create a new controller for the model
-f, --factory Create a new factory for the model
-m, --migration Create a new migration file for the model
-s, --seed Create a new seeder file for the model
-r, --resource Indicates if the generated controller should be a resource controller
Laravel 5.4 You can use
php artisan make:model --migration --controller --resource Test
This will create
1) Model
2) controller with default resource function
3) Migration file
And Got Answer
Model created successfully.
Created Migration: 2018_04_30_055346_create_tests_table
Controller created successfully.
We can use php artisan make:model Todo -a to create model, migration, resource controller and factory
You don't need to add --resource flag just type the following and laravel will create the whole desired resources
php artisan make:controller TodoController --model=todo
Instead of using long command like
php artisan make:model <Model Name> --migration --controller --resource
for make migration, model and controller, you may use even shorter as -mcr.
php artisan make:model <Model Name> -mcr
For more MOST USEFUL LARAVEL ARTISAN MAKE COMMANDS LISTS
If you are using Laravel as an only API add --api option:
php artisan make:model Post -a --api
To make mode, controllers with resources, You can type CMD as follows :
php artisan make:model Todo -mcr
or you can check by typing
php artisan help make:model
where you can get all the ideas
You can use -m -c -r to make migration, model and controller.
php artisan make:model Post -m -c -r
To make all 3: Model, Controller & Migration Schema of table
write in your console: php artisan make:model NameOfYourModel -mcr
How I was doing it until now:
php artisan make:model Customer
php artisan make:controller CustomersController --resource
Apparently, there’s a quicker way:
php artisan make:controller CustomersController --model=Customer
php artisan make:model modelname -mcr
to create model. Here -mcr stands for migrations components and resourses

Base table or view not found: 1146 Table 'db.ken_permissions' doesn't exist

Sometimes, when I type :
php artisan
php artisan migrate
etc
I get the message:
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.ken_permissions' doesn't exist (SQL: select * from `ken_permissions`)
Debugging, I can tell my problem happens in the artisan file in:
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
I had already check this answer, and didn't work:
bootstrap/app.php is clean,
I don't have app/start folder ( L5.1),
routes.php is clean
php artisan -v or php artisan --pretend doesn't work, because artisan fails before running it seems.
The only thing I have is in app/Providers
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
// Dynamically register permissions with Laravel's Gate.
foreach ($this->getPermissions() as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
One solution is to delete all my tables, then composer dump-autoload, and then it work again, but it constantly comes back.
Is it a way to trace what migration is failing?
Any idea why is it happening?
Tx!
Go to the App\Provider\AuthServiceProvider
if you use on boot method GateContract ($this->getPermission() etc), remove or add to comment all after parent::registerPolicies($gate); and done run php artisan migrate
Adding to watcher's answer here
Remove any lines requesting data from your model from these files to be sure artisan is not trying to load data from your non-existent table:
bootstrap/start.php
app/start/global.php
app/start/local.php
app/routes.php
Also be sure to un-register any service providers that utilize data from that table in their register or boot methods inside of app/config/app.php.
You can move your migrations to a database/temp folder and run your migrations one by one
php artisan migrate --path=database/temp
you will know which migration is causing problem.
NOTE
Also you can use
php artisan migrate --pretend to get the query you are trying to do.

Laravel 5.1 refresh and seed a single table

I'm looking to refresh and seed a single table in Laravel 5.1. Is this even possible?
I have tried the below, but it gives an error (incorrect syntax).
php artisan migrate:refresh --path=database/migrations/CreateTableTimesheet
If I use: php artisan migrate:refresh it just says:
Nothing to migrate
You could use migrate:refresh command that will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database :
php artisan migrate:refresh
And you may use the --class option to specify a specific seeder class to run individually :
php artisan db:seed --class=UserTableSeeder
The full code will be :
php artisan migrate:refresh
php artisan db:seed --class=UserTableSeeder
Hope this helps.
Its better to truncate your same table first and then seed:-
public function run()
{
Table::truncate();
//seed your table here
}
then you can run your same seeder like this:-
php artisan db:seed --class=YourSeeder
Maybe first just backup the database, drop it and check if whole seeding, migrating and refreshing mechanic works. But first dump artisan autoload.
I don't think any answer so far addresses the question of migrating and seeding a single table. So, given the migration file database/migrations/create_foo_table.php and the seed file database/seeds/FooTableSeeder.php, which contains the FooTableSeeder seed class, you can do the following:
php artisan migrate:refresh --path=database/migrations/create_foo_table.php
php artisan db:seed --class=FooTableSeeder
This will rollback, migrate and seed your Foo table. See: rolling back migrations and running seeders in the Laravel 5.1 documentation (at the time of writing this, Laravel 7.x is out and the syntax has not changed).
php artisan tinker
>>> App\Status::truncate()
Will clear the statuses table
So you can do
>>> App\{MODEL_CLASS}::truncate()
I found this quite useful when I don't want to clear all the tables, especially users.
include full table name
example
php artisan migrate:refresh --path='database/migrations/2014_10_12_000000_create_table_timesheet.php'
You can do it in two steps:
Refresh your specific table:
php artisan migrate:refresh --path=database/migrations/00_create_foo_table.php
Seed tables set in database/seeds/DatabaseSeeder.php:
composer dump-autoload
php artisan db:seed
=== Extra information ===
You can comment the seeders you don't want to use in DatabaseSeeder.php:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call([
FooSeeder::class,
// BarSeeder::class,
// UserSeeder::class,
]);
}
}
In this example, only database/seeds/FooSeeder.php will be passed.

Resources