bir tane responseapi diye bir kontroller oluşturalım aşağıdaki kodu yazalım.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public function apiResponse($resultType,$data,$message = null, $code = 200) { $response = []; $response['success'] = $resultType == ResultType::Success ? true : false; if(isset($data)) { if($resultType != ResultType::Error) { $response['data'] = $data; } if($resultType == ResultType::Error) { $response['errors'] = $data; } } if(isset($message)) { $response['message'] = $message; } return response()->json($response,$code); } //en alta bir class oluşturup class ResultType { const Success =1; const Information = 2; const Warning = 3; const Error = 4; } |
sonra hangi controllerda kullanacak isek onun fonksiyonların başlamadan class tanımının yapıldığı yerde (class contollerismi extends Controller) sonu controller diye biten kısma yukarıda oluşturduğumuz controller ismini verin. şimdi kullanıcağımız controllera gelip;
örneğin bir veri ekleme yapıyoruz
1 2 3 4 5 6 |
$validator = Validator::make($request->all(),[ 'email' => 'required|email' ]); if($validator->fails()) return $this->apiResponse(ResultType::Error,$validator->errors(),'Kontrol Hataları',422); |
bu rest apinin kaynağı ve yukarıdaki kodların yaratıcı olan cem abimizin rest api videosunda daha fazlasını bulabilirsiniz : https://www.udemy.com/course/laravel-ile-sifirdan-restful-api-uygulamalari-gelistirme/