KHN-プログラミングブログ-

laravel api

api

routes\api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/abc/data\Http\Controllers\AbcController@showList');

認証

routes\api.php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:api')->post('/abc/data/', 'App\Http\Controllers\AbcController@showList');

web

use Illuminate\Support\Facades\Route;

Route::get('/{any}', function () {
return view('app');
})->where('any', '.*');

Auth::routes();

APIエラー返却

    $res = response()->json(
        [
            'status' => $status,
            'errors' => $message->errors(),
        ],
        $status,
        ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'],
        JSON_UNESCAPED_UNICODE
    );
    throw new HttpResponseException($res);

モデルから配列へ

コントローラ― ⇒ データ取得
サービス ⇒ DB登録、join、foreachでリソースへ
リソース ⇒ データの整形

・サービス層

$modelData=User::find(Auth::id());

$data = new data();
foreach ($modelData as $key => $value) {
  $dataList[] = $data->datasResource($value);
}

・リソース層


class data(){

 public $id;

 public function datasResource($data)
  {
    $this->id = $data->id;

    return [
        "id" => $this->id,
      ];

}