How to set a comment on table using Laravel Schema Builder - laravel

How to set a comment on table using Laravel Schema Builder?
Column set:
public function up()
{
Schema::create('vendors', function (Blueprint $table)
{
$table->comment('not working - error'); // not working - error
$table->increments('id');
$table->string('vendor', 255)->comment('Some comment.');
$table->timestamps();
});
}
But for the table?

Well I don't have a nice answer for you, but at least it works.
Here it is:
public function up()
{
$tableName = 'vendors';
Schema::create($tableName, function (Blueprint $table)
{
$table->increments('id');
$table->string('vendor', 255)->comment('Some comment.');
$table->timestamps();
});
DB::statement("ALTER TABLE `$tableName` comment 'My comment'");
}
Just add a DB statement after creating your table.

Before Laravel 9, only columns were allowed to comment. Since laravel 9 the ability to comment on the table itself has been added.See this PR and the Blog article
If you would like to add a "comment" to a database table, you may invoke the comment method on the table instance. Table comments are currently only supported by MySQL and Postgres:
Schema::create('calculations', function (Blueprint $table) {
$table->comment('Business calculations');
// ...
});

Related

Undefined table: 7 ERROR: relation "users" does not exist

Friends I have the following problem with laravel migrations using postgres, and when I make changes to a migration, in this case the users table, but I get an error trying to remove an index from a key, can you help me please with this problem.
This is my migration code:
public function up() {
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->integer('idProfile');
$table->string('name');
$table->string('surname');
$table->string('email')->unique();
$table->string('photo')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
public function down() {
Schema::dropIfExists('users');
Schema::table('users', function (Blueprint $table){
$table->dropPrimary('id');
$table->dropIndex('users_pkey');
});
}
response from my console:
These are the indices that list me:
This is the structure of the final table:
Comments, things to improve I am all ears
When you are running migrate:refresh, you are running the down method. In your down method, you are dropping the table, and then trying to make edits to it, which is why you are getting "users" doesn't exist.
If this is just in a development env, make your changes in the up method, and remove everything apart from dropIFExists() from the down method.
It is highly recommended that don't change the migration file...
If you need to add a new row to your table (Consider you have mytable and you want to add myrow to the table), you can write in terminal :
php artisan make:migration add_myrow_to_mytable_table
after that , edit new added migration file!
remember to add the following code in down function :
Schema::table('mytable', function (Blueprint $table) {
$table->dropColumn('myrow');
});
after all, run :
php artisan migrate
If you want to remove a column from your table just follow this one :
Laravel Migrations - Dropping columns

How to let ID autoincrement start from certain number in Laravel Migration

I want to write a Laravel Migration auto increment ID as a primary key. I want to start this ID with a another value rather than 1. How can I do so ?
The migration up() function:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('phone');
$table->rememberToken();
$table->timestamps();
});
}
As of Laravel 8.x, you can now use this in your migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id()->startingValue(1200);
});
}
Source: https://laravel-news.com/laravel-auto-increment
You can use 2 methods
By Statement
DB::statement("ALTER TABLE your_table_here SET AUTO_INCREMENT = 9999;");
By inserting row and deleteing it.
DB::table('your_table_here ')->insert(['id' => 99999, ... ,'column' => 'value']);
DB::table('your_table_here ')->where('id', 99999)->delete();
Hope this helps
If you want your first ID in the table to be for example 10001.
If you are using Laravel 8.x
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->from(10001);
.
.
$table->timestamps();
});
}
add a record with id (desired id -1) and then delete it.
If you add a record with id 999, and then delete it, next record will have id 1000. You can also use SQL identity on your database
After Creating Migrations Just Go to your Mysql Database and put this query
ALTER TABLE users AUTO_INCREMENT = 1000;
try this ?
$table->increments('id')->start_from(10000);

How To Delete Multiple Data From Different Table

I have two tables like this
Books
id|book_name|writter_id
1|Artemis|1
Writters
id|writter_name
1|Jane Doe
both of the tables have a relationship like this
Book model return $this->belongsTo('App\Writter', 'writter_id');
Writter model return $this->hasMany('App\Book', 'writter_id');
books.index.blade.php
<p>{{ $book->writter->writter_name }}</p>
create books
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('book_name', 100)->unique();
$table->integer('writter_id')->unsigned();
$table->timestamps();
});
}
create writter
public function up()
{
Schema::create('writters', function (Blueprint $table) {
$table->increments('id');
$table->string('writter_name', 100);
$table->timestamps();
});
// Set Foreign Key
Schema::table('books', function (Blueprint $table) {
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
// Drop Foreign Key di kolom id_penulis di table books
Schema::table('books', function(Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
});
Schema::drop('writters');
}
Every time i delete the writters (for an example like jane doe above) the books data still have the writter_id So the index view throw me an error.
Is it possible to delete the data/row from the writters table, and delete the writter_id on the books in the same time?
Edit your books table migration and add foreign keys
$table->integer('writter_id')->unsigned()->nullable();
Schema::table('books', function($table) {
$table->foreign('writter_id')->references('id')->on('writters')->onDelete('set null');
});
As you see it sets null on writter delete
For make youre migration file, do you use foreign key ?
With foreign key you can add a method for on Delete.
Foreign key Documentation
migration.php
$table->integer('writter_id')->unsigned();
$table->foreign('writter_id)->references('id')->on('writters)->onDelete('cascade');
It's will be work
If you haven't set up foreign keys on your tables, removing a row from a table won't update the column referencing to that row.
To solve this we can set up foreign keys with the schema builder.
You can create a new migration file or modify your existing migrations if you don't care about your current database values.
Create a new migration file with php artisan make:migration. Inside that file, use these methods (don't forget to run composer require doctrine/dbal before running the migration):
public function up() {
// Remove current foreign keys and index.
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
$table->dropIndex('books_writter_id_foreign');
});
// Add new foreign and allow books to now have a writter by using `NULL`.
Schema::table('books', function (Blueprint $table) {
$table->integer('writter_id')->unsigned()->nullable()->change(); // Before changing a column, be sure to add the doctrine/dbal dependency to your composer.json file.
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('SET NULL');
});
}
public function down() {
// Revert to previous values.
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
$table->dropIndex('books_writter_id_foreign');
$table->integer('writter_id')->unsigned()->change();
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
Using ->onDelete('SET NULL') on the foreign key will set the value to NULL when the referenced value is deleted from the referenced table.
In your blade file you can now check if the book have a writer before outputting it:
#if ($book->writter_id)
<p>{{ $book->writter->writter_name }}</p>
#endif

Constrains in Foreign keys using database migrations

i cant figure out what im doing wrong, but everything looks ok, is giving me this errroof
Foreign key constraint is incorrectly formed
on my migrations, but i dont see any issue.
Migration table 1:
public function up()
{
Schema::create('candidate_industries', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('industry_id')->unsigned();
$table->foreign('industry_id')->references('id')->on('industries');
});
}
Migration number 2:
public function up()
{
Schema::create('candidate_regions', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('region_id')->unsigned();
$table->foreign('region_id')->references('id')->on('regions');
});
}
The issue was because "candidates" id column had a different dataType set, in my case was BigInt when i was trying to create a relation with a column of int.

laravel migration best way to add foreign key

Simple question: I'm new to Laravel. I have this migration file:
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
I want to update it to add onDelete('cascade').
What's the best way to do this?
Firstly you have to make your user_id field an index:
$table->index('user_id');
After that you can create a foreign key with an action on cascade:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
If you want to do that with a new migration, you have to remove the index and foreign key firstly and do everything from scratch.
On down() function you have to do this and then on up() do what I've wrote above:
$table->dropForeign('lists_user_id_foreign');
$table->dropIndex('lists_user_id_index');
$table->dropColumn('user_id');
In Laravel 7 it can be done in one line
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
let's say you have two tables student and section , you can refer the following two table structure for adding foreign key and making onDelete('cascade') .
Table -1 :
public function up()
{
Schema::create('student', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('address');
$table->string('phone');
$table->string('about')->nullable();
$table->timestamps();
});
}
Table - 2:
public function up()
{
Schema::create('section', function (Blueprint $table) {
$table->id();
$table->bigInteger('student_id')->unsigned()->index()->nullable();
$table->foreign('student_id')->references('id')->on('student')->onDelete('cascade');
$table->string('section')->nullable();
$table->string('stream')->nulable();
$table->timestamps();
});
}
hope it will help you -:)
you can read the full article from here .
Schema::create('roles',function(Blueprint $table){
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
Schema::create('permissions',function(Blueprint $table){
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles');
$table->string('permission');
});
As of Laravel 8:
$table->foreignIdFor(OtherClass::class)->constrained();
So simple :)
Make sure that the OtherClass migration file is running EARLIER (by filename date as usual).
If the OtherClass id is not autoincrementing, the otherclass_id would have a type of char instead of bigint, in which case->
Use this instead:
$table->foreignId('otherclass_id')->index()->constrained()->cascadeOnDelete();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first! The user_id column is declared unsigned because it cannot have negative value.
You may also specify options for the "on delete" and "on update" actions of the constraint:
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:
$table->dropForeign('posts_user_id_foreign');
If you are fairly new to Laravel and Eloquent, try out the Laravel From Scratch series available on laracasts. It is a great guide for beginners.
Laravel 7.x Foreign Key Constraints
Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:
Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
Source: https://laravel.com/docs/7.x/migrations
You should create a new migration file let's say 'add_user_foreign_key.php'
public function up()
{
Schema::table('lists', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('lists', function(Blueprint $table)
{
$table->dropForeign('user_id'); //
});
}
The run
php artisan migrate
If you want to add onDelete('cascade') on the existing foreign key, just drop the indexes and create them again:
public function up()
{
Schema::table('lists', function($table)
{
$table->dropForeign('lists_user_id_foreign');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('lists', function($table)
{
$table->dropForeign('lists_user_id_foreign');
$table->foreign('user_id')->references('id')->on('users');
});
}
Schema::table('posts', function (Blueprint $table) {
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
for versions before 7x;
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->unsignedBigInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
for version 7+;
Since this syntax is rather verbose, Laravel provides additional, terser methods that use conventions to provide a better developer experience. When using the foreignId method to create your column, the example above can be rewritten like so:
Schema::create('lists', function(Blueprint $table) {
$table->increments('id');
$table->string('title', 255);
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
The foreignId method is an alias for unsignedBigInteger while the constrained method will use convention to determine the table and column name being referenced. If your table name does not match the convention, you may specify the table name by passing it as an argument to the constrained method:
Schema::create('lists', function(Blueprint $table) {
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
});
source: https://laravel.com/docs/7.x/migrations#foreign-key-constraints
Clear and new in laravel
$table->foreignId('book_id')->constrained();
I was doing the same but got error " id not exist" => so I changed my migration file as below :
question table migration content:
$table->id() => should change to $table->increments('id')
definitions of foreign key in Reply table:
$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
now your foreign key will work.
Clear, modern and Straightforward approach
suppose parent: `Book Model` and `books table`
suppose child : `Page Model` and `pages table`
$table->foreignId('book_id')->references('id')->on('books');
where book_id is is the colomn name in child (pages table)
and id is the linkage between the Parent and Child tables, books and pages tables, and books is the table name to which we are going to link

Resources