Create single table using php artisan migrate - laravel

I have executed this command to create a 'Users' table:
php artisan migrate
But after that I have created one new migration file using below command and want to create a 'Contact us' table
php artisan make:migration contactus
After both commands whenever I execute below command for generating the 'Contact us' table i get the following error: Table 'users' already exists
php artisan migrate
This is my code of migration file Contactus :
public function up()
{
Schema::create('contactus',function(Blueprint $table){
$table->increments('id');
$table->string('email');
$table->string('message');
$table->timestamp('created_at')->nullable();
});
}
Is there any help i appreciated..

Sounds like Users migration file has been edited and needs re migrating. Run: php artisan migrate:refresh
Be warned This will remove anything stored within the database so ensure you have a Seeder setup to place any relevant content back into the database.
In the event you get an Laravel 5.4: Specified key was too long error on the re migrate open AppServiceProvider and add:
Schema::defaultStringLength(191); into the boot function
Ensure you add use Illuminate\Support\Facades\Schema; at the top of the AppServiceProvider file

For this issue SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes (SQL: alter table users add unique users_email_unique(email)) open your AppServiceProvider under App/Providers folder and add the below code:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}

Try running below command to drop and migrate all the table again:
php artisan migrate:fresh
Note:
If your users table already migrated or exist and you wish to create a new table run below command :
php artisan make:migration contactus
then
php artisan migrate

When using the CLI make sure not to blindly copy other migration files.
first run php artisan make:migration create_contact_us_table
Now open the migration file location at /database/migrations/create_contact_us_table.php
Edit your migration here, inside the UP function you should then have something like
public function up()
{
Schema::create('contact_us', function(Blueprint $table){
$table->increments('id');
//Other table content
});
}
After this you can run php artisan migrate again to run your migration.
If you keep getting this error, check your database and the migrations table.
It might not have saved that it already ran your previous migration. If this is the case remove all tables from the database and run php artisan migrate again. Should work then.

Related

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

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

Seeding from a package / Fixing ReflectionException

I have created a package which copies migrations and seeds to the respective directories in the base app.
However, unless I call (add) these within the run() function in the DatabaseSeeder class in the base app (app/database/seeds/DatabaseSeeder.php) when I run
php artisan migrate:refresh --seed
Then the seeds are not run. How can I automate this part so the user doesn't have to manually edit this file? Are there any artisan commands to manually run seeds?
Still don't completely understand how I got this to work, but for others;
In your boot method of your PackagenameServiceProvider use $this->publishes() to move the seeds and migrations to the base app
public function boot()
{
if (!$this->app->routesAreCached()) {
require __DIR__.'/../routes.php';
}
$this->publishes([
__DIR__.'/../DatabaseStuff/Migrations' => $this->app->databasePath().'/migrations',
__DIR__.'/../DatabaseStuff/Seeds/Example1Seeder.php' => $this->app->databasePath().'/seeds/Example1Seeder.php',
__DIR__.'/../DatabaseStuff/Seeds/Example2Seeder.php' => $this->app->databasePath().'/seeds/Example2Seeder.php',
]);
}
Have a copy of DatabaseSeeder with call methods pointing to the seeds you wish to run but make sure it's name-spaced correctly to where ever you have the files in your package.
namespace ExampleVendor\ExamplePackage\DatabaseStuff;
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call(\Example1Seeder::class);
$this->call(\Example2Seeder::class);
Model::reguard();
}
}
Now run the following commands. The critical command for me in this case was php artisan optimize
php artisan vendor:publish
composer dump-autoload
php artisan cache:clear
php artisan optimize
php artisan db:seed --class="ExampleVendor\ExamplePackage\DatabaseStuff\DatabaseSeeder"
Without php artisan optimize I kept getting
ReflectionException
Class ExampleVendor\ExamplePackage\DatabaseStuff\DatabaseSeeder does not exist
Hopefully this helps someone in the future.

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.

Artisan migrate:make --create command not making Schema::create()

I am following Dayle Rees's tutorial on migrations in Laravel 4. (And please see the link to understand my question). I am attempting to make some migration files using Artisan. I am at the paragraph beginning "We simply run...", followed by the example Artisan command:
php artisan migrate:make create_users --create --table=users
...followed by the resultant code (snippet):
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->timestamps();
});
}
But when I run the same artisan command, I don't get that. I get this instead:
public function up()
{
Schema::table('users', function(Blueprint $table)
{
//
});
}
Why?
Perhaps this is the result of a slightly later version of Laravel than Mr Rees was using for that tutorial, but the most annoying/puzzling thing is that the artisan command --create doesn't seem to work properly, ie. it is outputting
Schema::table()
instead of
Schema::create()
OK, for anyone reading this, I've found the answer. I think perhaps this is a mistake in Dayle Rees's tutorial. Following the docs, the artisan command should be
php artisan migrate:make create_users_table --create=users
So the moral of the story is that when the migration is for creating a table, the relevant command should be
php artisan migrate:make class_name --create=table_name
When modifying, the command is
php artisan migrate:make class_name --table=table_name

Resources