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

pouya's avatar
Level 1

Laravel Restful Api: Trying to get property of non-object

I'm working with Laravel 5.8 and I wanted to return some specific data of an Article.

So I made this Api Controller:

class ArticleController extends Controller
{
    public function index()
    {
        $articles = Article::find(1);
	    return new \App\Http\Resources\v1\Article($articles);
    }
}

And then created this Resource:

use Illuminate\Http\Resources\Json\Resource;

class Article extends Resource
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
           'art_title' => $this->art_title,
           'art_description' => $this->art_description
        ];
    }
}

So basically every article has a field named art_title as Article Title and art_description as Article Body.

But when I run this code, I get this error:

ErrorException (E_NOTICE) Trying to get property 'art_title' of non-object

I don't really know what on earth is going wrong here? So if you know, please help me with this cause I've got headache!

0 likes
1 reply
MahmoudTR's avatar

Try to check $articles value before passing it to the Resources try to do this:

public function index()
    {
        $articles = Article::find(1);
		dd($articles);
	    return new \App\Http\Resources\v1\Article($articles);
    }

What does it return?

I would Also Recommend to name Your resource class as ArticleResource as a better practice.

Please or to participate in this conversation.