How to build the database migration properly? - laravel

I'm setting up a laravel project (I'm beginner) to manage customers (a customer has many contracts and a contract has many different products). And I want to implement a CRUD method and generate pdf but I have an issue at the beginning, when I migrate my database. (this is the beginning so I guess it will hard for me...)
I wrote all my migrations (customer + contracts + products) and migrate them
customer (clients):
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Clients extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->Increments('id');
$table->string('name');
$table->string('company');
$table->string('email', 50);
$table->string('phone', 15);
$table->string('adress1', 50);
$table->string('adress2', 50);
$table->string('adresse3', 50);
$table->string('pays', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('clients');
}
}
Contracts (contrats)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Contrats extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
/* $table->unsignedBigInteger('clients_name');
$table->foreign('name')->references('name')->on('Clients'); */
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('contrats');
}
}
and products (produits)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Produits extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->Increments('id');
$table->foreign('name');
$table->string('description', 20);
$table->double('price');
$table->double('taxes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('produits');
}
}
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.03 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.02 seconds)
Migrating: 2019_10_15_131435_clients
Migrated: 2019_10_15_131435_clients (0.01 seconds)
Migrating: 2019_10_15_131454_contrats
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table (SQL: alter table contrats add constraint contrats_name_foreign foreign key (name) references Clients (name))
at
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table")
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
Please use the argument -v to see more details.
I expect to get a good migration to going ahead with this project
Thanks in advance for your help, cheers.

The foreign key column format must match the format of the column it's referencing on the other table, so instead of unsignedBigInteger, it should be string
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
/* $table->unsignedBigInteger('clients_name'); */
$table->string('name');
$table->foreign('name')->references('name')->on('clients');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
Tho it's highly recommended that you reference the primary key id instead
Proper way
Eloquent will make use of naming conventions to make proper relationships with less explicit code
clients
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateClientsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('company');
$table->string('email', 50);
$table->string('phone', 15);
$table->string('adress1', 50);
$table->string('adress2', 50);
$table->string('adresse3', 50);
$table->string('pays', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('clients');
}
}
contrats
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContratsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contrats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('contrats');
}
}
produits
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProduitsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients');
$table->string('description', 20);
$table->double('price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('produits');
}
}
Hope this helps
Bon Courage :)

write your function up for contrats migration like this
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate')->index();
$table->date('enddate')->index();
$table->timestamps();
});

Related

Cant do migration laravel 8

I'm new to laravel. Help please.
Error in the console when trying to migrate:
Migrating: 2022_03_15_224441_add_permission_menu_table
Illuminate\Database\QueryException
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `permission_menu` add constraint `permission_menu_menu_id_foreign` foreign key (`menu_id`) re
ferences `menus` (`id`) on delete cascade)
at D:\DEV\OpenServer\domains\crm.loc\vendor\laravel\framework\src\Illuminate\Database\Connection.php:712
708▕ // If an exception occurs when attempting to run a query, we'll format the error
709▕ // message to include the bindings with SQL, which will make this exception a
710▕ // lot more helpful to the developer instead of just the database's errors.
711▕ catch (Exception $e) {
➜ 712▕ throw new QueryException(
713▕ $query, $this->prepareBindings($bindings), $e
714▕ );
715▕ }
716▕ }
1 D:\DEV\OpenServer\domains\crm.loc\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501
PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")
2 D:\DEV\OpenServer\domains\crm.loc\vendor\laravel\framework\src\Illuminate\Database\Connection.php:501
PDOStatement::execute()
Migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddPermissionMenuTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('permission_menu', function (Blueprint $table) {
//
$table->integer('permission_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->bigInteger('menu_id')->unsigned();
$table->foreign('menu_id')->references('id')->on('menus')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
// Schema::table('permission_menu', function (Blueprint $table) {
// $table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
// $table->foreign('menu_id')->references('id')->on('menus')->onDelete('cascade');
// });
}
}
// the second migration file
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateMenusTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('menus', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('path');
$table->integer('parent');
$table->string('type');
$table->integer('sort_order')->default(100);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('menus');
}
}
Model File:
<?php
namespace App\Modules\Admin\Menu\Models;
use App\Modules\Admin\Role\Models\Permission;
use App\Modules\Admin\Users\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Menu extends Model
{Й
use HasFactory;
const MENU_TYPE_FRONT = 'front';
const MENU_TYPE_ADMIN = 'admin';
public function perms() {
return $this->belongsToMany(Permission::class, 'permission_menu');
}
public function scopeFrontMenu($query, $user) {
return $query->
where('type', self::MENU_TYPE_FRONT)->
whereHas('perms', function($q) use($user) {
$arr = collect($user->getMergedPermissions())->
map(function($item) {
return $item['id'];
}
);
$q->whereIn('id', $arr->toArray());
});
}
public function scopeAdminMenu($query, $user) {
return $query->where('type', self::MENU_TYPE_ADMIN);
}
public function scopeMenuByType($query, $type) {
return $query->where('type', $type)->orderBy('parent')->orderBy('sort_order');
}
}
I do not know what other details to describe to make it clearer what the problem is.
Please ask me if need what else.
I do not know what other details to describe to make it clearer what the problem is.
Please ask me if need what else.
I do not know what other details to describe to make it clearer what the problem is.
Please ask me if need what else.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddPermissionMenuTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('permission_menu', function (Blueprint $table) {
//
$table->bigInteger('permission_id')->unsigned();
Change integer to bigInteger on permission id
I decided so, for the permission_menus table I changed:
Schema::create('permission_menu', function (Blueprint $table) {
//
$table->integer('permission_id')->unsigned();
$table->foreign('permission_id')->references('id')->on('permissions')->onDelete('cascade');
$table->bigInteger('menu_id')->unsigned();
$table->foreign('menu_id')->references('id')->on('menus')->onDelete('cascade');
});
And for the menus table:
Schema::create('menus', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title');
$table->string('path');
$table->integer('parent');
$table->string('type');
$table->integer('sort_order')->default(100);
$table->timestamps();
});
And everything worked. Thanks!
I also tried to do this for the menus table left:
$table->increments('id');
And for the permission_menu table:
$table->integer('menu_id')->unsigned();
and everything worked too. It turns out to be a mismatch of two fields of two connected tables.

Laravel - 1215 Cannot add foreign constraint

I am trying to link up to three tables together but when I run my migration (using artisan) I keep getting an error:
General error: 1215 Cannot add foreign key constraint (SQL: alter table stores add constraint stores_sale_id_foreign foreign key (sale_id) references bikes (id))
Here is my migration file for stores:
class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->integer('sale_id')->unsigned();
$table->timestamps();
});
Schema::table('stores', function ($table){
$table->foreign('sale_id')->references('id')->on('bikes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}
store model:
class Store extends Model {
use HasFactory;
protected $table = 'stores';
protected $fillable = ['store_name', 'city', 'manager', 'sale_id'];
}
Edit:
bikes migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBikesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('bikes', function (Blueprint $table) {
$table->increments('id');
$table->string('make');
$table->string('model');
$table->string('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('bikes');
}
}
Instead of increments try $table->id()or $table->bigIncrements('id') for both tables.
Because the id column will then have the right type.
You will also need to set your foreign key column to $table->unsignedBigInteger('sale_id'); to set the right column type fore the foreign constraint.
And you will have to make sure that your bikes migration runs before your stores migration.
try this,
class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->integer('sale_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('sale_id')->references('id')->on('bikes')->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}
Use this code
class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->unsignedInteger('sale_id')->nullable();
$table->foreign('sale_id')->references('id')->on('bikes')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}
Note: Make sure there should not be a mismatch in foreign key field types.
Either change original migration from increments() to just
bigIncrements()
Or in your foreign key column do unsignedBigInteger() instead of unsignedInteger().

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint - Laravel

I'm trying to create a table to hold photos and link it to the ad (property id).
I'm getting this error
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
These are my migration files
2018_02_14_191609_create_property_adverts_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePropertyAdvertsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('property_adverts', function (Blueprint $table) {
$table->increments('id');
$table->string('address');
$table->string('county');
$table->string('town');
$table->string('type');
$table->string('rent');
$table->string('date');
$table->string('bedrooms');
$table->string('bathrooms');
$table->string('furnished');
$table->longText('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('property_adverts');
}
}
2018_02_18_165845_create_property_advert_photos_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePropertyAdvertPhotosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('property_advert_photos', function (Blueprint $table) {
$table->increments('id');
$table->integer('propertyadvert_id')->nullable();
$table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('property_advert_photos');
}
}
So the
Make it unsigned because you're using increments(). And move FK constraint part to a separate closure:
public function up()
{
Schema::create('property_advert_photos', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('propertyadvert_id')->nullable();
$table->timestamps();
});
Schema::table('property_advert_photos', function (Blueprint $table) {
$table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
});
}

Cannot migrate table using Laravel 4

When I try to migrate tables I created I get this error
PHP Fatal error: Class 'Users' not found in /var/www/html/laravel/vendor/laravel/
framework/src/Illuminate/Database/Migrations/Migrator.php on line 301
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Class 'Users' not found","file":"\/var\/www\/html\/laravel\/vendor
\/laravel\/framework\/src\/Illuminate\/Database\/Migrations\/Migrator.php",
"line":301}}
Here is my code:
Users table:
<?php
//Users Table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table) {
$table->increments('id');
$table->string('username');
$table->string('email');
$table->string('password');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down(){
}
}
Posts table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
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->string('m_keyword');
$table->string('m_disc');
$table->string('slug');
$table->integer('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
}
}
http://laravel.io/bin/zj31n
If you get the above error while running a migration, please run the below command
composer dump-autoload
For more info,
http://laravel.com/docs/master/migrations#running-migrations
Maybe what has gone wrong is that you did not call
php artisan migrate:rollback
before
php artisan migrate
Try to force delete the tables and try to migrate again.
And another thing. The 'user_id' column in the 'posts' table should be connected to the users table like this:
Schema::table('posts', function(Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
and I would call the create the table column like this:
$table->unsignedInteger('user_id');
or
$table->integer('user_id')->unsigned();

Laravel -Exception when running migration

I am attempting to run a migration but the following error is showing up:
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Call
to a member function increments() on a
non-object","file":"/Applications/MAMP/htdocs/khadamat/app/database/migrations/2014_03_17_165445_create-users-table.php","line":16}}{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Call
to a member function increments() on a
non-object","file":"/Applications/MAMP/htdocs/khadamat/app/database/migrations/2014_03_17_165445_create-users-table.php","line":16}}
This is the code including line 16:
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
$table->increments('id');
$table->string('firstname', 40);
$table->string('lastname', 40);
$table->string('dob', 40);
$table->string('email', 150)->unique();
$table->string('password', 64);
$table->string('address', 200);
$table->string('city', 40);
$table->string('country', 100);
$table->string('register_purpose', 40);
$table->timestamps();
}
any clear reason as to why this is happening? Thanks in advance
Better use artisan tool to generate migration... creating-migrations.. Some code from my projects migration table...
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateVideosTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('videos', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('description');
$table->string('image');
$table->text('embed');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('videos');
}
}

Resources