
laravel migration add foreign key to existing table
laravel migration add foreign key to existing table
In this session, we’ll try our hand at solving the "laravel migration add foreign key to existing table" puzzle by using the computer language.
You can add a foreign key to the existing table in laravel using migration. Laravel provides migration column type foreginId() which helps you to create a foreign key in an already existing table in your database.-
Create foreign key to an existing table in laravel 8
//Create migration file php artisan make:migration add_user_id_to_posts_table --table=posts //Create table structure using column type in the generated migration file //database\migrations\<2021_07_26_032616>_add_user_id_to_posts_table.php public function up() { Schema::table('posts', function (Blueprint $table) { $table->foreignId('user_id')->constrained(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('posts', function (Blueprint $table) { $table->dropForeign(['user_id']); }); } //Run artisan command to create a foreign key php artisan migrate
Laravel 8 has a foreignId() column type in migration schema builder. Which is used to create a foreign key in laravel with an UNSIGNED BIGINT equivalent column.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
Don't forget to share this article! Help us spread the word by clicking the share button below.
We appreciate your support and are committed to providing you valuable and informative content.
We are thankful for your never ending support.
Random Code Snippet Queries: Laravel
- Conditional validation in laravel
- Get current month records in laravel 7/8
- Undefined property: stdClass::$title
- Method Illuminate\Database\Eloquent\Collection::lists does not exist
- How to call model in blade laravel
- How to send email in laravel
- Ignore Records where a field has NULL value in Laravel
- How to pass two variables in HREF in laravel
- Composer create project laravel/laravel example app
- How to create belongstomany relation using custom name on custom pivot table
- Call to a member function pluck() on array
- Get count of filter data, while return a small set of records
- SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'user_id'
- How to add unique records in pivot columns of Laravel pivot table
- Send id with route Laravel
- SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel8.projects' doesn't exist
- Laravel API response format
- Recursive function example code PHP Laravel
- Print query in laravel
- How to add columns in existing table using migration in laravel
- PhpMyAdmin - Error The mysqli extension is missing
- Laravel create multiple records in Pivot table
- Method chaining in Laravel
- How to display pivot table column value in laravel
- How to return error message from controller to view in laravel