Php 如何添加';状态'';消息';用这个在拉威尔

Php 如何添加';状态'';消息';用这个在拉威尔,php,laravel,laravel-5,Php,Laravel,Laravel 5,如何添加“状态”和“消息”? 如果请求成功,状态将为true,并且在请求失败时添加消息:success和消息:false,例如无效数据,并添加适当的消息文本 这是我的控制器代码: <?php class authorController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */

如何添加“状态”和“消息”? 如果请求成功,状态将为true,并且在请求失败时添加消息:success和消息:false,例如无效数据,并添加适当的消息文本

这是我的控制器代码:

<?php

class authorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // Get autors

        $authors = Author::with('Authorprofile')->get();


        //Return collection of authors as a resource
        return authorResource::collection($authors);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //only one author with id
        $author = Author::find($id);
        return new authorResource (($author),($author->Authorprofile));
        //return one author


    }
}
目前的产出是:

{
    "data": {
        "id": 2,
        "username": "mithun",
        "firebase_id": "2",
        "name": "mithun",
        "email": "mithun@paperwiff.com",
        "email_verified": 0,
        "authorprofile": {
            "id": 2,
            "author_id": 2,
            "image": "mithun.jpg",
            "location": "Bangalore",
            "about": "Co-Founder",
            "created_at": "2019-10-23 03:06:00",
            "updated_at": null
        },
        "is_newsletter_subscribed": 0,
        "password": "mithun",
        "provider": "idk",
        "last_ip": "100.20.3255",
        "last_login": "2019-10-23 08:18:14",
        "login_counts": "1"
    }
}
我希望输出为:

{
     "Status":"True"
     "message:"Sucess"
     "data":{
 ,,,,,,,,,,,
,,,,,,,,,,,,
         }
}
改变这个

return authorResource::collection($authors);

公共功能索引()
{
$authors=Author::with('Authorprofile')->get();
$status=$authors->count()==0?false:true;
返回authorResource::collection($authors)->其他(['status'=>$status,'message'=>$status]);
}
公共活动展览($id)
{
试一试{
$author=author::findOrFail($id);
返回(新建authorResource($author,$author->Authorprofile))
->附加(['status'=>true,'message'=>true]);
}捕获(\Throwable$e){
返回响应()->json([
“数据”=>[],
“状态”=>false,
'message'=>false,
], 404);
}
} 

我希望代码对您有用


if($authors->count()>0){return$this->sendResponse($authors,'Success!');}else{return$this->sendrerror('No records founds!',[],401);}

如果有错误,如何将状态和消息设置为false?我可以尝试吗?我更改了答案。是的,我看到了,但问题是当它设置为false时,就像id不存在一样,它也会将状态设置为turbrother。实际上,我是php新手,所以这是一个什么陷阱(\Throwable$e)是否???如果指定的id不在数据库中,那么如何将状态设置为false并将错误消息发送出去。我可以使用Try吗?您可以设置“status”=>
$id!=无效的true:false
或者我可以添加if?如果像上面这样的语句,您检查
$id
如果不为null,则使
状态为true
否则为false
return authorResource::collection($authors);
$response = authorResource::collection($authors);
return ['status' => 200, 'response' => $response];