Laravel

Self relation in laravel eloquent

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
Author: Danyal
I'm skilled programmer with expertise in Vue.js/Nux.js for front-end development and PHP Laravel for back-end development. I excel in building APIs and services, and also have experience in web server setup & maintenance. My versatile skill set allows you to develop and maintain web applications effectively, from the user interface to the server-side functionality. I love coding with never ending learning attitude, thanks for visiting danya.dk