Reputation: 244
I have 2 tables - one with forum category name field called "disp_name" and "ID" called "forum_cat" and onother with forum posts id, forum post content and cat_id and more called "forum"
I have model "Forum_cats"
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forum_cats extends Model
{
protected $table = 'forum_cat';
public $timestamps = false;
}
and model "Forum"
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forum extends Model
{
protected $table = 'forum';
public $timestamps = false;
}
Controller :
public function index(){
$forum = Forum::orderBy('timestamp', 'desc')->paginate(20);
//next variable is for different place
$news = Neww::orderBy('date', 'DESC')->paginate(20);
return view ('lapas.pamata.index',[
'news'=>$news,
'forum'=> $forum,
]);
}
Blade:
@foreach($forum as $forums)
<li>
<div class="media">
<div class="media-body"> <a href="#" class="catg_title">
{{$forums->title}}</a> </div>
<i class="far fa-comment-alt"></i> {{$forums->comments}}
Kategorija:{{$forums->cat_id}}
</div>
</li>
@endforeach
so the view at the moment is like this where after "Kategorija" i have only category id
How to make after name "Kategorija" output field "disp_name" from table "forum_cat".
Someone can tell that there are lots of posts about my problem but i am trying to solve this problem all day. I know that its about hasOne, belongsTo and hasMany but i dont understand how correct us them on my code.
Upvotes: 0
Views: 322
Reputation: 1771
So, I assume (and still not sure) that forum belongs to a category.
Your Forum model should be:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forum extends Model {
protected $table = 'forum';
public $timestamps = false;
public category(){
return $this->belongsTo('App\Forum_cats', 'cat_id', 'id');
}
}
And your blade should be:
@foreach($forum as $forums)
<li>
<div class="media">
<div class="media-body"> <a href="#" class="catg_title">
{{$forums->title}}</a> </div>
<i class="far fa-comment-alt"></i> {{$forums->comments}}
Kategorija:{{$forums->category->disp_name}}
</div>
</li>
@endforeach
does that work for you? You also may consider eager loads:
https://laravel.com/docs/5.8/eloquent-relationships#constraining-eager-loads
Upvotes: 0