Eloquent Self Referential Relationship in Laravel?

eloquent-self-relatio

To get the relationship from same table eloquent model with parent and child relations ship.
Here is an example for menus which has parent asn child relationship.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    // fillable
    protected $fillable = ['title', 'slug','parent_id'];

    //each category might have one parent
    public function parent() {
        return $this->belongsToOne(static::class, 'parent_id');
    }

    //each category might have multiple children
    public function children() {
        return $this->hasMany(static::class, 'parent_id')->orderBy('id', 'asc');
    }
}

Accessing the relational data.

use App\Models\Category;
$categories = Category::with('children')->get();

it will gives the result with their children relation.

Retreieve the relation in blade view.

@foreach( $categories as $category )
  @if($category->parent_id == '')
  		<li>
  			<a href="{{ $category->slug }}" @if ($category->children->count()) class="dropdown-toggle" data-toggle="dropdown" @endif>{{ $category->title }} @if ($category->children->count())<b class="caret caret-right"></b>@endif</a>
  			@if ($category->children->count())
          <ul class="dropdown-menu">
            @foreach ($category->children as $child)
              <li><a href="{{ $child->slug }}" >{{ $child->title }}</a></li>
            @endforeach
          </ul>
        @endif
  		</li>
  	@endif
@endforeach
Please follow and like us:

Related Posts

Leave a Reply

Share