Laravel Multi-level category parent-child Helper view file to use easily

Categories - Laravel PHP Framework Tags - PHP Laravel   Maniruzzaman Akash   3 weeks ago   69   0

Hi, let’s add multi-level category system in laravel. -

Create Category migration -

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug')->unique();
            $table->string('logo')->nullable();
            $table->unsignedInteger('priority')->default(10);
            $table->boolean('enable_homepage')->default(true);
            $table->text('description')->nullable();
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->foreign('parent_id')->references('id')->on('categories');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('categories');
    }
};

Helper methods to print category in any select input

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Category extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'name2', 'slug', 'banner_image', 'logo_image', 'description', 'meta_description', 'parent_id', 'status', 'enable_bg', 'bg_color', 'deleted_at', 'created_by', 'updated_by', 'deleted_by'
    ];

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    /**
     * printCategory
     *
     * Prints the category on view directly
     *
     * @param integer $category_id
     * @param integer $layer
     * @return void
     */
    public static function printCategory($category_id = null, $layer = 3)
    {
        $html = "";
        $parentCategories = Category::select('id', 'name')->where('parent_id', null)->get();

        foreach ($parentCategories as $parent) {
            $selected = $category_id == $parent->id ? " selected" : '';
            $html .= "<option value='" . $parent->id . "'" . $selected . ">" . $parent->name . "</option>";

            // Get Sub Categories
            $childCategories = Category::select('id', 'name')->where('parent_id', $parent->id)->get();
            foreach ($childCategories as $child) {
                $selected = $category_id == $child->id ? " selected" : "";
                $html .= "<option value='" . $child->id . "' " . $selected . ">&nbsp;&nbsp;&nbsp;&nbsp;-- " . $child->name . "</option>";

                if ($layer === 3) {
                    // Get Sub Categories 2
                    $childCategories2 = Category::select('id', 'name')->where('parent_id', $child->id)->get();
                    foreach ($childCategories2 as $child2) {
                        if ($category_id === $child2->id)    $selected = " selected";
                        else  $selected = "";
                        $html .= "<option value='" . $child2->id . "' " . $selected . ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-- " . $child2->name . "</option>";
                    }
                }
            }
        }

        return $html;
    }
}

Use this print category methods -

**From Controller - **

/**
 * Show the form for creating a new resource.
 *
 * @return \Illuminate\Http\Response
 */
public function create()
{
	$categories = Category::printCategory(null, $layer = 2);
	return view('backend.pages.categories.create', compact('categories'));
}

**From View - **

<select class="form-control" id="parent_id" name="parent_id" style="width: 100%;">
      <option value="">Select Parent Category</option>
       {!! $categories !!}
</select>
Previous
PHP If-else-elseif and Switch-case
Next
PHP String Functions - All necessary String functions in PHP to manage strings better.