1

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');
    }
}
STA
  • 30,729
  • 8
  • 45
  • 59
Wina Chan
  • 79
  • 2
  • 9

3 Answers3

0

You should use:

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

I recommend to use camelCase for method names. I'm not sure how Datatables will handle this case.

Emil Georgiev
  • 529
  • 4
  • 15
0

In your ProdukController you need pass below code.

$result = Produk::with('Produk')->get();

When you dd($result);, you should see the related models in the relations array attribute.

To access the relations' properties from there, it is simply

$result->Produk->catagory_name
Yudiz Solutions
  • 4,216
  • 2
  • 7
  • 21
0

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;
sapphire
  • 20
  • 6