Company Model

Below code create company model & migration files.

php artisan make:model Company -m

If you want to delete a record but not physically from the database, then you can perform soft delete. When using the soft delete, a deleted_at field is added to a table to keep the track of date and time at which the model was deleted. To enable, we need to two things; first, add use SoftDeletes in a model (need to add use Illuminate\Database\Eloquent\SoftDeletes;) and $table->softDeletes(); in data migration class

Since we are working on 'name', 'addressLine1', 'addressLine2', 'city', 'country', 'telephone', 'fax','emailAddress', 'country_id', hence we add it to company Model and Migration.

Replace model class with below code.

Note: Please use the copy button to copy the source code.

We need to include the following import statement(s)
use Illuminate\Database\Eloquent\SoftDeletes;

Model class
class Company extends Model { use HasFactory; use SoftDeletes; protected $fillable = [ 'name', 'addressLine1', 'addressLine2', 'city', 'country', 'telephone', 'fax', 'emailAddress', 'country_id', ]; }
Migration class

To add a foreign key to the table, we use this convention $table->foreignId('country_id')->constrained(); tableName_primaryKey In this case, this table has foreign key relationship with country table on id column.

In up() method of the migration file, we define the table schema e.g. string (will convert to varchar). In chain, we add a property like ->unique (ensure the field is unique in the database table) or ->nullable (the field will be nullable)

For all  Available Column Types, please refer to https://laravel.com/docs/8.x/migrations

Replace the up() and down() methods with the code below.

public function up() { Schema::create('companies', function (Blueprint $table) { $table->id(); $table->string('name')->unique(); $table->string('addressLine1'); $table->string('addressLine2')->nullable(); $table->string('city')->nullable(); $table->string('telephone')->unique(); $table->string('fax')->nullable(); $table->string('emailAddress')->unique(); $table->timestamps(); $table->foreignId('country_id')->constrained(); $table->softDeletes(); }); } public function down() { Schema::dropIfExists('companies'); }

Since we need company id to users table, we add an additional migration

php artisan make:migration add_company_id_to_users_table
public function up() { Schema::table('users', function (Blueprint $table) { $table->foreignId('company_id')->constrained(); }); } public function down() { Schema::table('users', function (Blueprint $table) { $table->dropForeign(['company_id']); }); }

To create/update the table to database, we need to run artisan migrate command

php artisan migrate