Use case:
Suppose you need to store endless parent child objects in single table.
Example:
Categories
Comments
Users
In my case, I would like to store users with relation of (Administrator & Manager) in single table. Where each manager is belongs to an administrator.
Users Table: Table contains following fields.
id
name
email
password
parent_id
created_at
updated_at
Migration:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->integer('parent_id')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
User Model:
Let’s see how laravel model will handel this.
In user model, I create a public method parent with BelongsTo annotation.
/** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function parent() { return $this->belongsTo(User::class); }
What will be the query when I need to get all users with parent relation.
User::with('parent')->get();
You can perform various queries via eloquent depending on your usecase.
Find more examples of eloquent.
How to get user’s parent information in view.
@if ($user->parent_id) {{ $user->parent->name }} @endif