vendredi 19 juin 2020

Using Eloquent to retrieve the parent category name?

i have a simple application for recursive hasMany relationship with unlimited subcategories the code is running without a problem but it's not retrieving the parent category name or title.

when i tried to loop through the data coming from the DB it have the parent id but not the parent category name i need to get the parent category name here is the code for both controller and model

CategoryController.php

<?php

namespace App\Http\Controllers;

use App\Category;
use Illuminate\Http\Request;

class CategoryController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
         $parentCategories = Category::where('parent_id',1)->get();
         return view('welcome', compact('parentCategories'));
    }
}
?>

Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $guarded = [];

    public function subcategory(){

        return $this->hasMany('App\Category', 'parent_id');

    }
}
?>


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2YfdWeQ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire