Search code examples
laraveldatatablemodeleloquent-relationship

How to get the "catagory name" in Laravel?


How to get "category name" show in the product table not as "category_id"?

I already try to combine any solutions for this. But still can't solve this prob. I'd love to hear other suggestions from the masters here.

Category Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Kategori extends Model
{
    use HasFactory;
    protected $casts = [
        'updated_at' => 'datetime:d/m/Y, H:i:s'
    ];

    public function Kategori()
    {
        return $this->hasMany('App\Models\Produk');
    }
}

Product Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Produk extends Model
{
    use HasFactory;
    protected $casts = [
        'updated_at' => 'datetime:d/m/Y, H:i:s'
    ];

    public function Produk()
    {
        return $this->belongsTo('App\Models\Kategori', 'kategori_id');
    }
}

Category Table enter image description here

Product Table enter image description here

Product Controller >>>> in my opinion may be my prob at here, but not so sure.

<?php

namespace App\Http\Controllers;

use App\Models\Produk;
use RealRashid\SweetAlert\Facades\Alert;
use Yajra\Datatables\DataTables;
use Illuminate\Http\Request;

class ProdukController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function json(){
        return Datatables::of(Produk::all())->make(true);
    }
    public function index(){
        return view('back.produk.show');
    }
}

Solution

  • Pass the other model using your relationship

    public function json(){
        return Datatables::of(Produk::with('produk')->get())->make(true);
    }
    

    to which say that is named $produks, you can access it as

    $produk->produk->nama;
    

    As a side note, Do name your relationships the names of the other model. for example, in the Kategori class, the relationship to Produk should be named produks (it is a hasMany relationship) as opposed to Kategori. Similarly, in the Produk class, the relationship to Kategori being named kategori() to which from the above answer you access it like

    $produk->kategori->nama;