Laravel Migration to a new Server/DB - laravel

I am trying to migrate to a new DB in a different host. However, when I run php artisan migrate, it's giving me an error. Laravel is looking for a specific table(permissions table in this case, I have eloquent relationships set up) in my app. Obviously, a new DB is completely empty. How can I run the migration to a new DB in a new host? What am I missing here?
In Connection.php line 664:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cf.permissions' doesn't exist (SQL: select * from `permissions`)
In PDOConnection.php line 63:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cf.permissions' doesn't exist
In PDOConnection.php line 61:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cf.permissions' doesn't exist
Permission Migration File;
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePermissionRoles extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('permissions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('label');
$table->timestamps();
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('label');
$table->timestamps();
});
Schema::create('permission_role', function (Blueprint $table) {
$table->integer('permission_id')->unsigned();
$table->integer('role_id')->unsigned();
$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']);
});
Schema::create('role_user', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('role_id')
->references('id')
->on('roles')
/* ->onDelete('cascade') */
;
$table->foreign('user_id')
->references('id')
->on('users')
/* ->onDelete('cascade') */
;
$table->primary(['role_id', 'user_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('permissions');
Schema::dropIfExists('role_user');
Schema::dropIfExists('permission_role');
Schema::dropIfExists('roles');
}
}
AppServiceProvider File;
public function boot()
{
$this->registerPolicies();
foreach ($this->getPermissions() as $permission) {
Gate::define($permission->name, function ($user) use ($permission) {
return $user->hasRole($permission->roles);
});
}
}
protected function getPermissions()
{
return Permission::with('roles')->get();
}

In your getPermissions() method, check if your schema permissions and roles exists and return values accordingly using Schema's hasTable() method. This way migrate commands would not hinder with service provider's methods.
Note that once the 2 tables are set(after a successful migration), this action from your service provider will always be executed.
<?php
protected function getPermissions(){
if(Schema::hasTable('permissions') && Schema::hasTable('roles')){
return Permission::with('roles')->get();
}
return collect([]);
}

Related

Laravel Table Migration: Cannot add foreign key constraint

I'm trying to create foreign keys in Laravel however when I migrate my table using artisan I am thrown the following error:
Modules migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModulesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->string('module_name');
// foreign key
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('modules');
}
}
Lesson migration table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLessonTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('module_id')->unsigned();
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
Schema::table('lesson', function(Blueprint $table) {
$table->foreign('module_id')->references('id')->on('modules');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('lesson');
}
}
Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. Users, Clients, Projects, Tasks, Statuses, Priorities, Types, Teams. Ideally, I want to create tables that hold this data with the foreign keys, i..e clients_project and project_tasks, etc.
Hope someone can help me to get started.
Add unsignedBigInteger for module_id column
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->unsignedBigInteger('module_id');
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
$table->foreign('module_id')->references('id')->on('modules');
});
Your foreign_key field and your id should be of the same type, for example, if modules.id is bigIncrements, your foreign_key inside your Lesson table also should be bigInteger.
Lesson Migration File
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->integer('module_id')->unsigned()->nullable();
$table->foreign('module_id')->references('id')->on('modules')->onDelete('cascade');
$table->text('content');
$table->integer('created_by')->unsigned();
$table->integer('updated_by');
$table->string('enabled');
$table->string('position');
$table->timestamps();
});
Note: You should make sure, your Modules table migration is running before Lesson table migration.

How to use Spatie Role and Permission For Admin?

**This is the Migration file which is created By Spatie and I want to use spatie for the admin panel and every tutorial having the usage for the User model and I have both user and admin model. I did not understand how to connect this with my admin model or admin db table because by default it is taking the user model and user table **
class CreatePermissionTables extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
$tableNames = config('permission.table_names');
$columnNames = config('permission.column_names');
if (empty($tableNames)) {
throw new \Exception('Error: config/permission.php not loaded. Run [php artisan config:clear] and try again.');
}
Schema::create($tableNames['permissions'], function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('guard_name');
$table->timestamps();
});
Schema::create($tableNames['roles'], function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('guard_name');
$table->timestamps();
});
Schema::create($tableNames['model_has_permissions'], function (Blueprint $table) use ($tableNames, $columnNames) {
$table->unsignedBigInteger('permission_id');
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_permissions_model_id_model_type_index');
$table->foreign('permission_id')
->references('id')
->on($tableNames['permissions'])
->onDelete('cascade');
$table->primary(['permission_id', $columnNames['model_morph_key'], 'model_type'],
'model_has_permissions_permission_model_type_primary');
});
Schema::create($tableNames['model_has_roles'], function (Blueprint $table) use ($tableNames, $columnNames) {
$table->unsignedBigInteger('role_id');
$table->string('model_type');
$table->unsignedBigInteger($columnNames['model_morph_key']);
$table->index([$columnNames['model_morph_key'], 'model_type'], 'model_has_roles_model_id_model_type_index');
$table->foreign('role_id')
->references('id')
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary(['role_id', $columnNames['model_morph_key'], 'model_type'],
'model_has_roles_role_model_type_primary');
});
Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) {
$table->unsignedBigInteger('permission_id');
$table->unsignedBigInteger('role_id');
$table->foreign('permission_id')
->references('id')
->on($tableNames['permissions'])
->onDelete('cascade');
$table->foreign('role_id')
->references('id')
->on($tableNames['roles'])
->onDelete('cascade');
$table->primary(['permission_id', 'role_id'], 'role_has_permissions_permission_id_role_id_primary');
});
app('cache')
->store(config('permission.cache.store') != 'default' ? config('permission.cache.store') : null)
->forget(config('permission.cache.key'));
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
$tableNames = config('permission.table_names');
if (empty($tableNames)) {
throw new \Exception('Error: config/permission.php not found and defaults could not be merged. Please publish the package configuration before proceeding, or drop the tables manually.');
}
Schema::drop($tableNames['role_has_permissions']);
Schema::drop($tableNames['model_has_roles']);
Schema::drop($tableNames['model_has_permissions']);
Schema::drop($tableNames['roles']);
Schema::drop($tableNames['permissions']);
}
}

Laravel Cannot update or delete a parent row a foreign key constraint fails

i am trying to run command php artisan migrate:rollback and it throw me the error cannot update or delete a parent row foreign key constraint fails
there is now issue when i run command php artisan migrate it successfully migrate my all tables but when i run rollback command it throw me the error the error is on my purpose_of_visits migration
public function up()
{
Schema::create('purpose_of_visits', function (Blueprint $table) {
$table->increments('id');
$table->string('purpose', 100);
$table->string('description', 197);
$table->integer('speciality_id')->unsigned()->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->softDeletes();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('updated_by')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('purpose_of_visits');
}
and my specialities migration:
public function up()
{
Schema::create('specialities', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50);
$table->string('description',250)->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$table->softDeletes();
$table->integer('created_by')->unsigned()->nullable();
$table->integer('updated_by')->unsigned()->nullable();
$table->foreign('created_by')->references('id')->on('users')->onDelete('cascade');
$table->foreign('updated_by')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('specialities');
}
i cant figure out where is the issue even i am using onDelete('cascade')
your help will be highly appreciated!
Make sure you have speciality_id, created_by and updated_by in the fillable property of your purpose_of_visits model. See docs here.
For example on your model.
protected $fillable = ['speciality_id','created_by','updated_by'];
Remove the foreign key constraints of the table before dropping it.
public function down()
{
Schema::table('purpose_of_visits', function (Blueprint $table) {
$table->dropForeign(['speciality_id']);
$table->dropForeign(['created_by']);
$table->dropForeign(['updated_by']);
});
Schema::dropIfExists('purpose_of_visits');
}
Sorry For the Late reply There are Two Situation Where this error can be thrown
For Eg:
I have tables such as posts, authors
And here is my post table Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->unsignedInteger('author_id');
$table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
and here is my authors table migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAuthorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('authors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('authors');
}
}
Situation 1:
now if the posts table migration runs before the authors table migration it my throw the error
Situation 2:
in some cases if you miss unsigned it may throw error
Solution1:
use
$table->unsignedInteger('speciality_id');
$table->unsignedInteger('speciality_id');
$table->foreign('author_id')->references('id')->on('specialities')->onDelete('cascade');
instead of this
$table->integer('speciality_id')->unsigned()->nullable();
$table->foreign('speciality_id')->references('id')->on('specialities')->onDelete('cascade');
if it again fails use this
try composer dumpautoload
adn then
Schema::disableForeignKeyConstraints();
At the beggining of the migration
and at the end
Schema::enableForeignKeyConstraints();
eg: you migration may look like
public function up()
{
Schema::disableForeignKeyConstraints();
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
Schema::enableForeignKeyConstraints();
}
and if the same error throws please attach Error Screenshot and commet below
Hope it helps

Laravel: 1060 Duplicate column name while running migrations

I am getting the following error when running migrations:
PDOException::("SQLSTATE[42S21]: Column already exists: 1060 Duplicate
column name 'role_id'")
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
if(!Schema::hasTable('users')) {
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Schema::table('users', function (Blueprint $table) {
$table->integer('role_id')->unsigned();
$table->string('first_name')->nullable();
$table->string('middle_name')->nullable();
$table->string('last_name')->nullable();
$table->string('city')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('role_id');
});
}
}
I have deleted most of the migrated tables as it gives duplication issues. Could that be related to my existing problem ?
try running these commands in your terminal:
composer dump-autoload // updates whatever you changed in your migration
php artisan migrate:fresh // migrates migration from the start
if these doesn't not work, post your column structure so we can understand more about your problem.

keep getting error when trying to add foreign key constraints

I have the book migration file:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('title');
$table->string('Author');
$table->text('Book_description');
$table->integer('user_id');
$table->foreign('user_id')->refrences('id')->on('users');
$table->boolean('donated')->default(false);
$table->string('country',150);
$table->string('city',30);
$table->string('path');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
but when I run the following command:
php artisan migrate:refresh
I get the following error:
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 (SQL: alter table books add constraint books_user_id_foreign foreign key (user_id) references users ())
I have searched Google but could not find what is wrong and also I have read Laravel 5.6 docs but I could not figure out what is wrong.
There's a typo: It has to be ->references('id') instead of ->refrences('id').
Try with this
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
});
Schema::table('books', function($table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}

Resources