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.
Related Queries
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
- SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.post_id' in 'where clause
- How to fetch single row data from database in laravel
- How to check data inserted or deleted in pivot after toggle method
- Add class to body in laravel view
- Display message with session flash using bootstrap alert class in laravel
- How to check query string exists or not in laravel blade
- Get the post details if it has at least one comment in comments table
- Laravel append URI in route
- Create record with unique slug in laravel
- How to display user profile after login in laravel
- Get id of last inserted record in laravel
- Send id with route Laravel
- Laravel delete all rows older than 30 days
- How to get list of all views file in laravel
- Global scope in Laravel with example
- Remove several global scope from query
- After image selected get validation error in laravel
- Cannot end a section without first starting one
- Where to use whereNotNull eloquent in laravel
- How to create static page in Laravel
- How to display validation error in laravel
- Link storage folder in laravel 8
- How to get id of next record in laravel
- How to automatically update the timestamp of parent model in Laravel
- How to delete record in Laravel with ajax