Drop views and tables - mysql

I have a migration that create a view in MySQL. when I run
PHP artisan db:wipe
it drops all the tables but not the view.
when I run
php artisan migrate
it says base table or view already exists.
my migration
public function up()
{
DB::statement("
CREATE VIEW contacts_view
AS
SELECT
*
FROM
accounts
where isContact='yes';
");
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
// Schema::dropIfExists('contacts_view');
DB::statement("DROP VIEW contacts_view");
}

To avoid errors when running your migration with existing view, sue CREATE OR REPLACE
public function up()
{
DB::statement("
CREATE OR REPLACE VIEW contacts_view
AS
SELECT
*
FROM
accounts
where isContact='yes';
");
}
The view will always be recreated.

Related

How to resolve SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table in laravel?

I created Three migration tables user_container table is for storing user details, admin_table is for storing admin details, blog_table is for storing blogs .admin can create blogs so that's why i make a foriegn key relationship for admin to blogs table .when i try to migrate the tables i am getting the following error
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1824 Failed to open the referenced table 'admin_table' (SQL: alter table `blogs_table` add constraint `blogs_table_admin_id_foreign` foreign key (`admin_id`) references `admin_table` (`id`))
please help me to fix this issue i am not getting where did i mistake..
migration table structure
2021_08_11_170129_create_Blogs_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('blogs_table', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('price');
$table->string('country');
$table->longText('description');
$table->integer('rating');
$table->longText('image');
$table->unsignedInteger('admin_id');
$table->foreign('admin_id')->references('id')->on('admin_table');
$table->timestamps();
//$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('blogs_table');
}
}
2021_08_12_121933_create_admin_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateAdminTable extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('admin_table', function (Blueprint $table) {
$table->id();
$table->string('firstName');
$table->string('lastName');
$table->string('email')->unique();
$table->string('mobile');
$table->string('password');
$table->timestamps();
//$table->softDeletes();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('admin_table');
}
}
You are trying to run the migration on your Blogs Table first and after that, you run the migration on Admin Table.
Laravel migration takes the timestamp at the beginning of the file to decide which migration should be migrated first in the sequence.
Make sure you create an admin table first before the Blog table (this also applies to any tables that have references). Or simply just rename the file (change the timestamp) like E.g:
2021_08_12_121933_create_admin_table.php
2021_08_11_170129_create_Blogs_table.php
To this:
2021_08_11_121933_create_admin_table.php
2021_08_12_170129_create_Blogs_table.php
Then run php artisan migrate:fresh to refresh your migration.
When you're setting up the foreign key $table->foreign('admin_id')->references('id')->on('admin_table'); the table admin_table doesnt exist yet.
Change the migration name of the admin_table to be run before that of the blog one.
2021_08_11_121933_create_admin_table.php
instead of
2021_08_12_121933_create_admin_table.php

A space in front of column in table when created from Laravel migration

Does anyone run into an issue like me, have extra spaces when I created a table via Laravel migration?
And I'd re-ran couples of time for this migration file and still created extra spaces.
My environment.
Laravel 5.6
PHP 7.2
MySQL 5.7.23
Here are my pictures and migration content.
Schema::create('plugin_packages', function (Blueprint $table) {
$table->char('id', 36)->primary();
$table->char('plugin_id', 36)->nullable();
$table->char('plugin_package_device_model_id', 36)->nullable();
$table->char('plugin_package_os_version_id', 36)->nullable();
$table->string('version_number');
$table->string('file');
$table->timestamps();
$table->softDeletes();
$table->foreign('plugin_id')->references('id')->on('plugins')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('plugin_package_device_model_id', 'ppdm_id_foreign')->references('id')->on('plugin_package_device_models')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('plugin_package_os_version_id', 'ppov_id_foreign')->references('id')->on('plugin_package_os_versions')->onUpdate('cascade')->onDelete('cascade');
});
Thank you.
------2019.03.21 updated-------
Got \u0096\u0096 in front of plugin_package_os_version_id column.
[{"id":"14f0c766-341c-4262-9a33-0b8fc3063cad","plugin_id":"b3f09e90-cd8b-4e18-9b5e-c9176a5ea898","plugin_package_device_model_id":"a7a630e3-3fac-40c3-b3ed-61d54eb91d6f","\u0096\u0096plugin_package_os_version_id":"623eaf52-09dd-4837-aa9e-79e4f930d654","version_number":"1.0.1","file":"uploads\/application-x-dosexec\/2019-03-12\/FECEdgeServiceSETUP_3484fe18556c19479f8b6caf5c60ec98.exe","created_at":"2019-03-21 14:12:43","updated_at":"2019-03-21 14:12:43","deleted_at":null}]
------2019.03.21 updated 2-------
If I change from
$table->char('plugin_package_os_version_id', 36)->nullable();
to
$table->char('ppov_id', 36)->nullable();
It works as expected.
As an image is shown:
still cannot be identified where it caused the issue.
-----2019.03.21 update 3-------
Whole content of the migration file
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePluginPackagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('plugin_packages', function (Blueprint $table) {
$table->char('id', 36)->primary();
$table->char('plugin_id', 36)->nullable();
$table->char('plugin_package_device_model_id', 36)->nullable();
$table->char('plugin_package_os_version_id', 36)->nullable();
$table->string('version_number');
$table->string('file');
$table->timestamps();
$table->softDeletes();
$table->foreign('plugin_id')->references('id')->on('plugins')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('plugin_package_device_model_id', 'ppdm_id_foreign')->references('id')->on('plugin_package_device_models')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('plugin_package_os_version_id', 'ppov_id_foreign')->references('id')->on('plugin_package_os_versions')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('plugin_packages');
}
}
try to run these following commands in your terminal:
composer dump-autoload
php artisan config:cache
php artisan migrate:fresh

Creating a settings table in Mysql and fetching with eloquent in laravel

I want to create a settings table with 2 columns (Setting, value) and setting will hold something like SITE_NAME and Value will be the value like "Facebook" or "Youtube" or something like that. This will hold the site name, logo url and etc. How would i create this and most importantly how would i fetch the info with Laravel eloquent without a id field.
First things first.
Your table requires a primary key. Will that be a varchar field, according to your example? MySql's search by name is WAY SLOWER than comparing an with an index (integer). What it does in theory (google can explain it better) is somewhat converting text to an index and validating it, whereas with an index it just accesses it. I see nothing wrong - infact, I support - the idea of having an id column as a primary key. If duplicates is your worry, then you can set unique on your column site_name.
Create a migration to create a table
php artisan make:migration settings_table
Fill your migration code
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class SettingsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
//$table->increments('id'); This will come in hand, trust me
$table->string('site_name',255)->unique();
//If you really insist on having site_name as primary key, then use the line below
// $table->string('site_name',255)->primary();
$table->string('value',255);
//$table->timestamps(); Do you need?
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('settings');
}
}
Create a Eloquent model
php artisan make:model Setting
Fill your Eloquent model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['site_name','value'];
//protected $table = ['settings'] Only if you really need it
//Usually, if you take Laravel's approach, Models are singular version of the tables, that are in plural, but you can work it as you like
}

Migrations do not follow timestamp order

I am working with Laravel 5.4 trying to run my migrations. I have read that the order of execution follows the timestamps of the migration files. But this is not the case, as I receive the following error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table `aplicantes` add constraint `aplicantes_pais_id
_foreign` foreign key (`pais_id`) references `pais` (`id`))
These are my migrations files:
2014_01_01_100004_create_pais_table.php
2014_01_01_100005_create_departamentos_table.php
2014_01_01_100006_create_aplicantes_table.php
And this is where migration complains:
class CreateAplicantesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('aplicantes', function (Blueprint $table) {
$table->increments('id');
$table->string('nombre');
$table->unsignedInteger('pais_id');
$table->foreign('pais_id')->references('id')->on('pais');
$table->timestamps();
});
}
}
This is my Pais migration:
public function up()
{
Schema::create('pais', function (Blueprint $table) {
$table->increments('id');
$table->string('nombre');
$table->timestamps();
});
}
When I inspect the database, only the aplicantes table is created, which is the third in the order. I guess that is why the migration fails because the aplicantes table is being created first, which references a table that does not exist yet.
EDIT:
I have updated my migrations, creating an individual file for the foreign keys of every table. I'm getting an error when migrate:refresh, an access violation while dropping a foreign key, and I presume it's because of the same reason: migration is performing in alphabetical order, not by the timestamp.
UPDATE:
I had to rename every migrations file and now it seems working. Seems that migrate only care about days field in the naming convention of the migration files, not the seconds, as I was working with.
Despite that I see a correct order of migrate in migrations table, it complains of dropping foreign keys when I have my migration file like this:
class AddAplicantesForeignKey extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('aplicantes', function (Blueprint $table) {
$table->foreign('pais_id')->references('id')->on('pais')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('aplicantes', function(Blueprint $table)
{
$table->dropForeign('pais_id');
});
}
}
I manage to disable the complains by turn off the foreign key constraints check in my migration create table:
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('aplicantes');
}
I am not happy with this solution, but it seems to only be working this way.

Laravel table refuse to be registered on migrations table and rollbacked or migrated

I have a migration table refuse to be registered in migrations tables ..
2014_10_12_000000_create_users_table 1
2014_10_12_100000_create_password_resets_table 1
2016_03_21_010421_create_orders_table 1
2016_03_21_010549_create_types_table 1
2016_03_21_010722_create_materials_table 1
2016_03_21_010814_create_ratings_table 1
2016_03_21_011205_create_costs_table 1
2016_03_21_012114_create_locations_table 1
2016_06_02_181122_create_assignments_table 1
2016_06_25_001455_create_bills_table 1
2016_07_26_195012_create_roles_table 1
2016_08_06_205440_create_permissions_table 1
2016_08_11_013917_create_material_order_table 1
file : 2017_03_04_201351_create_permission_role_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePermissionRoleTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
/**
* Run the migrations.
*
* #return void
*/
Schema::create('permission_role', function (Blueprint $table) {
$table->integer('permission_id')->unsigned()->index();
$table->integer('role_id')->unsigned()->index();
$table->foreign('permission_id')
->references('id')
->on('permissions')
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on('roles')
->onDelete('cascade');
$table->primary(['permission_id', 'role_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('permission_role');
}
}
this is the migration ..
i tried composer dump also it does not appear ..
it refuse to migrate ..
i deleted manually but have the same error upon migrate:refresh or migrate after rollback.
Finally that is the error :
[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'permission_role' already exists (SQL: create table `permission_role` (`permission_id` in
t unsigned not null, `role_id` int unsigned not null) default character set utf8 collate utf8_unicode_ci)
[PDOException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'permission_role' already exists
table info : innoDB .
github repo : link
https://github.com/lifesound/fixgate
You already have the table permission_role, now your migrations table is not aligned with your database.
If you know what to do you can edit manually the migrations table, restore the file you discarded and run "composer dump-autoload" followed by a migrate
Probably the best way is to drop manually all the tables (including migrations table) and rerun migrate. If you can drop all your tables.
I found the solution by changing the id column in the permission table to (increments) instead of (enum) .. Although it was what i did not want ,
so i have to add the enum to other column ..
In these cases as i learned from that error .. with 2 days lost testing :
Be sure of your tables order . relational table should come after
parent tables .
composer dump when changing any file name , delete or add .
The relational columns should be unsigned and index .
Use migrate:reset to delete all your migrations . then migrate again.
If you changed the database config , don't forget to clear config .
Be sure that your table is innoDB .