Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

henryoladj's avatar

Trying to get tags associated to a post

i am trying to show the category associated with the post i made but it is giving Trying to get property 'name' of non-object

[{{$news->tags->name}}]
0 likes
50 replies
Snapey's avatar

assuming you are iterating over news, then it may be that all tags are missing (not loaded) or just one news item is missing a tag

for now, change this code to stop it blowing up

[{{$news->tags->name ?? 'no tag here'}}]

then if all news are missing tag, post the controller code here because you need to eager load the tag model

siangboon's avatar

if tags is a collection you may need to loop each tag to get the name property of the tag...

henryoladj's avatar

@snapey This is the controller code

<?php

namespace App\Http\Controllers;

use App\News;
use App\Tag;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class NewsController extends Controller
{
    function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $tag=null)
    {   
        if($tag){
            $tag=Tag::where('name',$tag)->first();

            

            $news=$tag->news()->paginate(15);
        }else{
            $news= News::paginate(15);
        }
        return view('categories.news',compact(['news','tag']));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('news.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validate

        $this->validate($request,[
            'subject'=>'required|min:10',
            'tags' => 'required',
            'body' => 'required|min:20'

        ]);
        
        //store
        $news=auth()->user()->news()->create($request->all());

        $news->tags()->attach($request->tags);

        //redirect
        return redirect()->route('news.index');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function show(News $news)
    {   
        
        
        return view('news.single', compact('news'));
    }

    

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function edit(News $news)
    {
        return view('news.edit', compact('news'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, News $news)
    {
        if(auth()->user()->id !== $news->user_id){
            abort(401, "Please Login");
        }

        $this->validate($request,[
            'subject'=>'required|min:10',
            'body' => 'required|min:20'
        ]);

        $news->update($request->all());

        return redirect()->route('news.show', $news->slug)->withMessage('News Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\News  $news
     * @return \Illuminate\Http\Response
     */
    public function destroy(News $news)
    {   
        if(auth()->user()->id !== $news->user_id){
            abort(401, "Please Login");
        }

      
        $news->delete();
        $news= News::paginate(15);
        return view('categories.news', compact('news'));
    }
}

Using this code [{{$news->tags->name ?? 'no tag here'}}] it is showing [no tag here].

Snapey's avatar

What sort of relationship is tags?

henryoladj's avatar

@snapey

Tag.php

public function news()
    {
        return $this->belongsToMany(News::class);
    }

News.php

public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
ERashdan's avatar

Since you are using "belongsToMany" relationship that's mean news may have many tags therefore you can't request $news->tags->name

If your relationship news is belong to one tag use in News.php

public function tags() {
  return $this->belongsTo(Tag::class);
}

But if it's many to many you should use it define your which tag in $news for example

$news->tags->first()->name;
ERashdan's avatar

@henryoladj Since your relation between news and tags is many to many (You are using belongsToMany)

$news->tags

Will return many tags you can solve it by using foreach

@foreach($news->tags as $tag)
{{ $tag->name }}
@endforeach

It's depends on your table schema If you share your table schema for tags and news it will be better

henryoladj's avatar

@emadiga this did not work

i have a table for tags i have a table for news

i have a table that contains the news_id and tags_id.

I am trying to get the tag name for individual post

Snapey's avatar

One News item can belong to many tags

So you cannot say $news->tags->name because there could be multiple tags and Laravel cannot pick just one to get the name from.

as well as foreach, you can do something like

{{ explode(', ', $news->tags->pluck('name')) }}
ERashdan's avatar

Did foreach return empty result Can you try

{{ $news->tags()->count() }}

What's the result of this ?

If it's return zero then pivot table is empty for this "news" object

jlrdw's avatar

I haven't checked, but does Jeffrey have a video on tags.

And you know tags is not required for friendly URL you can name routes anyting you want to

My/pretty/face

Can point to any controller method, I've never used tags.

I guess I look at tags as an extra unnecessary step, but that's just my opinion.

henryoladj's avatar

@jlrdw i am not trying to make the tags url, i want to display tags associated to each posts on each posts pages.

Do you understand?

ERashdan's avatar

try

{{ $news->tags()->first()->name }}

Make sure there's element called name for tag If you are using laravel 5.6+ try

<?php
dump($news->tags()->first());
?>

Please reply with result

henryoladj's avatar

@emadiga this [ {{ $news->tags()->first()->name }} ] worked, What about getting the route link to the tag. How would that work??

henryoladj's avatar

Thanks i just figured it out.

How do i display the tag name on the page title? <title></titlte>

jlrdw's avatar

Jut pass it along using a -with statement ->with('title' , $title)

Or include in in a compact statement, either way.

henryoladj's avatar

Tried this

<?php
$title=$tag->id;
?>

and it did not work

jlrdw's avatar

No pass it from controller to view in the return view statement.

Make a variable first.

henryoladj's avatar

I did like this

public function index(Request $request, $tag=null)
    {   
        if($tag){
            $tag=Tag::where('name',$tag)->first();
            $news=$tag->news()->paginate(15);
        }else{
            $news= News::paginate(15);
        }
        $title = $tag->name;
        return view('categories.news',compact(['news','tag']));
    }

and it is showing this $title on the Title Bar

Snapey's avatar

If you are happy using

{{ $news->tags()->first()->name }}

then why are you using a pivot table so that news can have many categories.

Life would be a lot easier if news item could only have one tag

henryoladj's avatar

@snapey Even after doing

<?php
$category = $tag->name;
?>

the category name changed on the title... But after i make a post i get this error Trying to get property 'name' of non-object

Controller.php
public function index(Request $request, $tag=null)
    {   
        if($tag){
            $tag=Tag::where('name',$tag)->first();
            $news=$tag->news()->paginate(15);
        }else{
            $news= News::paginate(15);
        }
        return view('categories.news',compact(['news','tag']));
    }
siangboon's avatar

First make sure yourself clear on what you are calling, is an object or value. if it's collection of objects then you need to loop each object in order to call the property...

you should ensure the object exist before you can call the property of object....

if($tag) <= if $tag is true you may find the data what if $tag cannot find a record?

how about "else" without declare/assign proper/default $tag object, the tag is empty/null, and you call the $tag->name, hence you get error: "Trying to get property 'name' of NON-OBJECT

Next

Please or to participate in this conversation.