Laravel Restful API

Its not difficult to create restful API with Laravel.

First create controller for handling data

php artisan make:controller api/FxInfoController --api

This will create the controller with some dummy functions index() show() store() update() destory()

Update the api/FxInfoController.php

<?php
 
 namespace App\Http\Controllers\api;

 use App\Http\Controllers\Controller;
 use Illuminate\Http\Request;
 use App\FxInfo;
 
 class FxInfoController extends Controller
 {
     /**
      * Display a listing of the resource.
      *
      * @return \Illuminate\Http\Response
      */
     public function index()
     {
         return response()->json(FxInfo::all(), 200);
     }

     /**
      * Store a newly created resource in storage.
      *
      * @param  \Illuminate\Http\Request  $request
      * @return \Illuminate\Http\Response
      */
     public function store(Request $request)
     {
         $fxInfo = UserInfo::create($request->all());
 

         return response()->json($fxInfo, 201);
     }

     /**
      * Display the specified resource.
      *
      * @param  int  $id
      * @return \Illuminate\Http\Response
      */
     public function show(FxInfo $fxInfo)
     {
         return response()->json($fxInfo, 200);
     }
 

     /**
      * Update the specified resource in storage.
      *
      * @param  \Illuminate\Http\Request  $request
      * @param  int  $id
      * @return \Illuminate\Http\Response
      */
     public function update(Request $request, FxInfo $fxInfo)
     {
         $fxInfo->update($request->all());

         return response()->json($fxInfo, 200);
     }
 
     /**
      * Remove the specified resource from storage.
      *
      * @param  int  $id
      * @return \Illuminate\Http\Response
      */
     public function destroy(FxInfo $fxInfo)
     {
         $fxInfo->delete();
 

         return response()->json(null, 204);
     }
 } 

Now update the routes/api.php to define where to go
e.g. http://127.0.0.1:8000/api/fx will go to api\FxInfoController.php index() function

Route::get(‘fx’, ‘api\FxInfoController@index’);
Route::get(‘fx/{fxInfo}’, ‘api\FxInfoController@show’);
Route::post(‘fx’, ‘api\FxInfoController@store’);
Route::put(‘fx/{fxInfo}’, ‘api\FxInfoController@update’);
Route::delete(‘fx/{fxInfo}’, ‘api\FxInfoController@destroy’);

A simple Restful API is done, we can try it with Postman

This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *