
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
- Call to a member function getRelationExistenceQuery() on array in Laravel
- How to pass query string to url in laravel
- The Pusher library requires the PHP cURL module. Please ensure it is installed
- Rendering HTML from database table to view in Laravel
- Pass variable from blade to controller Laravel
- How to display order by null last in laravel
- Send post data from controller to view
- Display data in table using foreach in Laravel
- Include External CSS and JS file in Laravel
- Laravel create multiple records in Pivot table
- Redirect from www to non www in laravel using htaccess
- Laravel get single row by id
- Fatal error: Uncaught Error: Class "Illuminate\Foundation\Application" not found
- How to add active class to menu item in laravel
- How to get all route list
- How to validate website url in laravel using validaiton
- How to create belongstomany relation using custom name on custom pivot table
- How to customize or Change validation error messages
- How to get single column value in laravel
- How to delete record in Laravel with ajax
- Credit card validation in laravel
- How to check records exist in loaded relationship in Laravel blade view
- Laravel insert query not working
- Drop foreign key column in Laravel using migration
- Ajax POST request in laravel