How to limit probable entry from user in migration? - laravel

What if I try to limit possible entries in migration level in Laravel. For instance i have a migration:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('type')
$table->timestamps();
});
}
Now I want to accept anything from image, post, bio for the type column. if the user try to save anything except the 3 options, i want the DB to deny. How can I do so ?

You can use an enum column allowing only the defined values.
https://laravel.com/docs/8.x/migrations#column-method-enum
$table->enum('type', ['image', 'post', 'bio']);

Related

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);

Laravel roles and how to show them

Hello there I have a Laravel Question. I need to create a table that shows the following data. Client details ( client name, surname, contact numbers, email address, address). The Client should be in two categories which are Cooperate and Individual Client. Here is a snippet of what i what i did in my client migration file. I wanted to ask on how best to distinguish between them using roles.
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->increments('id');
$table->string('client_name');
$table->string('client_surname');
$table->smallInteger('phone_number');
$table->string('email_address');
$table->string('address');
$table->timestamps();
});
}
You can create a new column in your table called categorie.
public function up()
{
Schema::table('clients', function (Blueprint $table) {
$table->string('categorie');
});
}
You can return the clients in your controller via a simple query, like this:
$individual_clients = Client::where('categorie', 'individual')->get();
$cooperate_clients = Client::where('categorie', 'cooperate')->get();

How to set a comment on table using Laravel Schema Builder

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');
// ...
});

Drop and then create same columns in current up migration function

Schema::table('users', function (Blueprint $table) {
$table->dropTimestamps();
$table->dropColumn(['email', 'bio']);
$table->string('email', 20)->unique()->after('id');
$table->string('bio', 150)->after('surname');
$table->timestamps();
});
That is what I've got now. So, I have the columns existing atm in my table, but I want to modify and re-arrange them a bit. But when I run the migration, I get SQL error that email column exists. And I will probably get the same error for the bio and timestamps as well. I kind of understand why this happens, so what am I asking is just for a workaround.
Is it possible to make what I want inside one single migration, or I have to create a migration for deleting the columns and then a separate migration for creating them the way I want?
Just break the schema up into two calls
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropTimestamps();
$table->dropColumn(['email', 'bio']);
});
Schema::table('users', function (Blueprint $table) {
$table->string('email', 20)->unique()->after('id');
$table->string('bio', 150)->after('surname');
$table->timestamps();
});
}
This way the change is occurring in one migration with two database calls.
Consider that if you drop the columns, you will lose ALL THE DATA contained therein. Normally this is a very bad and dangerous idea. If you instead need to simply change parameters, you should use the change() function to make the required modifications to your schema. This will convert the existing data to the best of your databases's ability.
NEVER DROP COLUMNS on an in-use database unless you absolutely know what you're doing.
public function up()
{
Schema::table('users', function (Blueprint $table) {
// Add the unique constraint, for example
$table->string('email', 20)->unique()->after('id')->change();
// Add the length to the bio, for example
$table->string('bio', 150)->after('surname')->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
// Remove length and constraints
$table->string('email')->unique(false)->change();
$table->string('bio')->change();
});
}

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