Laravel Restful Api:在 null 上调用成员函数 toBase()
我正在使用Laravel 5.8,我想从API路线中检索一些数据:
Route::prefix('v1')->namespace('Api\v1')->group(function(){
Route::get('/articles','ArticleController@index');;
});
然后我也制作了一个资源收集和一个控制器:
articleCollection.php
:
public function toArray($request)
{
return parent::toArray($request);
}
ARTICLECONTROLLER
:
public function index()
{
$articles = Article::all();
return new ArticleCollection($articles);
}
现在它正确显示了数据:
{"data":[{"art_id":3,"art_cat_id":15,"art_author_id":23973,"art_title":"\u0627\u062d\u06cc\u0627\u06cc...
但是当我将资源收集更改为此时:
public function toArray($request)
{
return [
'title' => $this->art_title,
'desc' => $this->art_description,
];
}
尝试在控制器中找到特定的文章:
public function index()
{
$articles = Article::find(1);
return new ArticleCollection($articles);
}
我会以某种方式获得此错误:
致命性 呼叫null上的成员函数tobase()
那么这里出了什么问题?我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其更改
为:
这是因为查找仅返回一条记录,并且您要将其转换为集合,通过使用
get()
您可以按照您的意图返回一个集合。Change this:
to this:
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.