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 AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Kategori extends Model { use HasFactory; protected $casts = [ 'updated_at' => 'datetime:d/m/Y, H:i:s' ]; public function Kategori() { return $this->hasMany('AppModelsProduk'); } }
Product Model
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Produk extends Model { use HasFactory; protected $casts = [ 'updated_at' => 'datetime:d/m/Y, H:i:s' ]; public function Produk() { return $this->belongsTo('AppModelsKategori', 'kategori_id'); } }
Product Controller >>>> in my opinion may be my prob at here, but not so sure.
<?php namespace AppHttpControllers; use AppModelsProduk; use RealRashidSweetAlertFacadesAlert; use YajraDatatablesDataTables; use IlluminateHttpRequest; 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'); } }
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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;
Method 2
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.
Method 3
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0