Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
});
OR
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
// one_line code for foreign in laravel
$table->foreignId('user_id')->constrained()->onDelete('cascade');
public function up()
{
Schema::create('replies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->text('body');
$table->unsignedBigInteger('question_id');
$table->integer('user_id')->unsigned();
$table->foreign('question_id')->references('id')->on('questions')->onDelete('cascade');
$table->timestamps();
});
}
//acording to laravel 7>=
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
//for deffirent table
$table->foreignId('user_id')->constrained('users');
//for taking action
$table->foreignId('user_id')
->constrained()
->onUpdate('cascade')
->onDelete('cascade');
$table->foreign('column_name')->references('id')->on('table_name')->onDelete('cascade');
Schema::table('posts', function (Blueprint $table) {
$table->foreignId('user_id')->constrained();
});
$table->foreignId('user_id')
->constrained()
->onUpdate('cascade')
->onDelete('cascade');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')
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');
$table->foreign('category_id')->references('id')->on('categories')->onUpdate('cascade')->onDelete('cascade');
Schema::table('portfolios', function (Blueprint $table) {
$table->string('filter_alias');
$table->foreign('filter_alias')->cascadeOnDelete()->references('alias')->on('filters');
});