Laravel 5.1 : Migrate existing database - laravel

https://github.com/Xethron/migrations-generator
I migrated my database structure into Laravel using php artisan migrate:generate command with the help of the extension above. But there's a small problem, my primary key's aren't named as id, I rather used a different convention by adding a prefix for each of them like user_id, product_id, photo_id, etc. All of these are auto incremented, of course.
Here's my current create_users_table.php file inside my migrations folder. I defined user_id to override the default id option, is that the correct use?
<?php
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->primary('user_id');
$table->integer('user_id', true);
$table->string('name', 500);
$table->string('email', 500);
$table->string('password', 500);
}
);
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
I read that I need to add something like below, but I'm not sure where to define protected $primaryKey since my class extends Migration rather than Eloquent.
class CreateUsersTable extends Eloquent {
protected $primaryKey = 'user_id';
}
I'm getting the following error when I go to /auth/login page, which I think causes because of the user_id usage rather than id. How can I fix it?
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.id' in 'where clause' (SQL: select * from `users` where `users`.`id` = 5 limit 1)

You need to specify your non-default primary key in your User model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {
protected $primaryKey = 'user_id';
You will need to do this for all Models that don't use id as their primary key.

Related

why foreign key not get setted in laravel migrations

I made an exam-question relationship, every exam has less than 200 questions, but when I run migrations, I go to the PHPMyAdmin and I don't find the foreign key set, it's only a bigint(20) unsigned column and not linked to the exams table.
exam model
<?php
namespace App\Models;
use App\Models\Question;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Exam extends Model
{
use HasFactory;
protected $fillable = [
//
];
public function questions(){
return $this->hasMany(Question::class);
}
}
question model
<?php
namespace App\Models;
use App\Models\Exam;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Question extends Model
{
use HasFactory;
function exam(){
return $this->belongsTo(Exam::class);
}
}
exam migration
<?php
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateExamsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('exams', function (Blueprint $table) {
$table->id();
$table->string('examHash')->unique();
//..
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('exams');
}
}
questions migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->foreignId('exam_id')->constrained();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('questions');
}
}
I've tried to:
Use this
$table->foreign('exam_id')->references('id')->on('exams');
but
Key column 'exam_id' doesn't exist in table
EDIT:
it can be caused because my engine is not InnoDB, regularly I change the engine to InnoDB to create foreign keys
The method foreignId will only create an UNSIGNED BIGINT and not a foreign key constraint. To also create a constraint you need to call constrained() afterward.
Try this:
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->foreignId('exam_id')->constrained();
$table->timestamps();
});
You can also find more information in the documentation.
Try to add the constrained method when you define the foreign key in question's migration, change:
$table->foreignId('exam_id');
to:
$table->foreignId('exam_id')->constrained();
the problem as I've mentioned in the question is in the engine. so I wrote
$table->engine = 'InnoDB';
in both of question and exam tables...

How to create table in laravel without created_at and Updated_at column using migration

Can anyone know how to create Table in laravel without created_at and Updated_at Column in table using a migration.
I try this Following code but it's still create created_at and Updated_at column in table:-
Migration Laravel :-
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateNewusersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('newusers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('name');
$table->string('email', 100)->unique();
$table->bigInteger('phone_no');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('newusers');
}
}
Add this in your model
public $timestamps = false;

camelCase format table name in Laravel

I want to create a table by migration with name "blogOST".
But Laravel create a table is "blogpost".
In Laravel, how to use migration to create table name with camelCase format.
This is my migration code
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOrderDetailTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('blogPost', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 100);
$table->dateTime('createdAt');
$table->dateTime('updatedAt');
$table->dateTime('deletedAt')->nullable();
$table->charset = 'utf8';
$table->collation = 'utf8_general_ci';
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('orderdetail');
}
}
Mostly its a common way to usesnake casefor table names and column names, Not onlyLaravel` but also other languages uses same practice.
In Laravel Eloquent Model automatically maps to lower case plural table name. You can explicitly mention different table name if you want using protected $table = 'my_table_name';
So its Laravels default behavior.

How Laravel defines name of the foreign-key as default in Model file?

I am new at Laravel and I am wondering how actually Laravel determines default foreign key name.
According to the Laravel document, it says "Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id".
Then, in this case↓, the default foreign key supposed to be named as info_id as the document says.
app/Models/Item.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
public function itemInfo()
{
return $this->hasOne(‘App\Models\ItemInfo’);
}
}
I just changed the name of infofunction as infooo THEN, no error happened. It do works...
What I expected was an error occurs because I thought Laravel would name the default foreign key as infooo_id and there is not such a column name in the tables.
It means Laravel does not determine the default foreign key name by the method name, doesn`t it?
Then what portion actually Laravel determine the default foreign key from?
These are the migration files of tables:
database/YYYY_MM_dd_hhiiss_create_items_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create(‘items’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists(‘items’);
}
}
YYYY_mm_dd_hhiiss_create_item_infos_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateItemInfosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create(‘item_infos’, function (Blueprint $table) {
$table->increments(‘id’);
$table->integer(‘item_id’)->unsigned();
$table->string(‘genre’);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists(‘item_infos’);
}
}

Change tables structures with migration without losing data?

I have read several threads about this but still not exactly my problem.
So in the users table I have a column called role, which is enum type and has two available values: 1 and 2. I set 2 as the default one. Now I want to change it to 1, for example. I created a new migration, ran php artisan migrate and encounter this error:
[Illuminate\DatabaseQueryException]
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'role' (SQL: alter table `u
sers` add `role` enum('1', '2') not null default '1')
[PDOException]
SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'role'
Here is code in my CreateUsersTable migration file:
$table->enum('role', ['1', '2'])->default('2');
And I did the same in the new UpdateUsersTable migration file:
$table->enum('role', ['1', '2'])->default('1');
And by the way I can not use php artisan migrate:refresh because it will delete all my data. Where am I doing wrong?
$table->enum('role', ['1', '2'])->default('1')->change();
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Migrations\Migration;
class UpdateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
DB::statement('ALTER TABLE `users` MODIFY `role` DEFAULT 1;');
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
DB::statement('ALTER TABLE `users` MODIFY `role` DEFAULT 2;');
}
}
Adapted from this answer to another question
In order to do this you have to add ->nullable() or ->default() to every field you add to the migration file.
create a new migration file
php artisan make:migration add_role_to_users_table --table=users
open the created migration file (database\migrations\2021_12_01_050851-add_role_tables.php) and add below code.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddRoleToUsers extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->enum('role', ['1', '2'])->default('1')->comment('1 - admin, 2 - normal'); //added
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('role'); //added
});
}
}
?>
Now migration refresh
php artisan migrate:refresh --path=/database/migrations/2021_12_01_050851-add_role_tables.php

Resources