php - Laravel BelongsToMany Get Category Name in Index List
Get the solution ↓↓↓I'm new to Laravel and to php.
I created my categories for my news system.
On my page where I list all my news, I have the following problem while showing the category to which the news is linked.
I'm bringing the category of my article with ID 5.
But I can't do that for other news.
How can I do this on my page where I list all my news?
Thank you to everyone in advance.
My Controller Page
public function index()
{
$data = News::all()->sortByDesc('created_at');
$parentcategory= News::find(5)->parent_category()->limit(1)->get();
return view ('SS.haber.index',compact('data','parentcategory'));
}
My Model Page
public function parent_category()
{
return $this->belongsToMany('App\Models\SS\NewsCategory', 'news_category_s');
}
My Views
<td> @foreach ($parentcategory as $pc) {{$pc->category_name}} @endforeach </td>
I think the problem I'm having in this area is very simple.
I was only able to pull the category of news number 5 id.
I don't know how to print categories of other data.
If public function update ($ id) {
it would work the way I did.
But I should be able to pull the categories of all records on the index page.
Answer
Solution:
my enlish is a liitle poor. I guess maybe you need try to plus a with('parent_category') after all()
$data = News::all()->with('parent_category')->sortByDesc('created_at');
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.