Как добавить 'Status', 'message' с этим в laravel - PullRequest
0 голосов
/ 24 октября 2019

Как я могу добавить «Статус» и «Сообщение»? Состояние будет истинным, если запрос выполнен успешно, и добавьте сообщение: success и message: 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


    }
}

Вот код ресурса:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'firebase_id' => $this->firebase_id,
            'name' => $this->name,
            'email'=> $this->email,
            'email_verified' =>$this->email_verified,
            'authorprofile'=>$this->authorprofile,
            'is_newsletter_subscribed' =>$this->is_newsletter_subscribed,
            'password'=>$this->password,
            'provider'=>$this->provider,
            'last_ip'=>$this->last_ip,
            'last_login' =>$this->last_login,
            'login_counts'=>$this->login_counts
        ];
    }
}

Вывод на данный момент:

{
    "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":{
 ,,,,,,,,,,,
,,,,,,,,,,,,
         }
}

Ответы [ 3 ]

1 голос
/ 24 октября 2019
public function index()
{
    $authors = Author::with('Authorprofile')->get();

    $status = $authors->count() === 0 ? false : true;

    return authorResource::collection($authors)->additional(['status' => $status, 'message' => $status]);
}

public function show($id)
{
    try {
        $author = Author::findOrFail($id);
        return (new authorResource ($author, $author->Authorprofile))
            ->additional(['status' => true, 'message' => true]);
    } catch (\Throwable $e) {
        return response()->json([
            'data' => [],
            'status' => false,
            'message' => false,
        ], 404);
    }
} 
0 голосов
/ 24 октября 2019

Я надеюсь, что код будет работать для вас

if ($hors-> count ()> 0) {return $ this-> sendResponse ($ авторы, 'Success!');} else {return $ this-> sendError ('Нет записей!', [], 401);}

0 голосов
/ 24 октября 2019

Измените

return authorResource::collection($authors);

на

$response = authorResource::collection($authors);
return ['status' => 200, 'response' => $response];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...