Laravel Restful Api: Call to a member function toBase() on null

389 views Asked by At

I'm using Laravel 5.8 and I wanted to retrieve some data from an Api route:

Route::prefix('v1')->namespace('Api\v1')->group(function(){
    Route::get('/articles','ArticleController@index');;
});

Then I made a Resource Collection and a Controller as well:

ArticleCollection.php:

public function toArray($request)
    {
        return parent::toArray($request);
    }

ArticleController:

public function index()
    {
        $articles = Article::all();
        return new ArticleCollection($articles);
    }

Now it properly shows data:

{"data":[{"art_id":3,"art_cat_id":15,"art_author_id":23973,"art_title":"\u0627\u062d\u06cc\u0627\u06cc...

But when I change the Resource Collection to this:

public function toArray($request)
    {
        return [
            'title' => $this->art_title,
            'desc' => $this->art_description,
        ];
    }

And trying to find an specific article in the Controller:

public function index()
    {
        $articles = Article::find(1);
        return new ArticleCollection($articles);
    }

I will get this error somehow:

FatalThrowableError Call to a member function toBase() on null

So what's going wrong here? How can I solve this issue?

1

There are 1 answers

2
Salman Malik On BEST ANSWER

Change this:

public function index()
    {
        $articles = Article::find(1);
        return new ArticleCollection($articles);
    }

to this:

public function index()
    {
        $articles = Article::where('id',1)->get();
        return new ArticleCollection($articles);
    }

This is because the find returns just one record and you are converting that to a collection, by using get() you can return a collection as you intend to here.