smartcomputing123

routes--api.php (common.v1)

Apr 11th, 2023 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 7.13 KB | Software | 0 0
  1. <?php
  2.  
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\Route;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Database\Schema\Blueprint;
  7.  
  8. /*
  9. |--------------------------------------------------------------------------
  10. | API Routes
  11. |--------------------------------------------------------------------------
  12. |
  13. | Here is where you can register API routes for your application. These
  14. | routes are loaded by the RouteServiceProvider within a group which
  15. | is assigned the "api" middleware group. Enjoy building your API!
  16. |
  17. */
  18.  
  19.  
  20.  
  21. Route::get('/hello', function () {
  22.     return( 'hello');
  23. });
  24.  
  25. /* initialize the table for REST API service */
  26. Route::get('/init', function () {
  27.    Schema::dropIfExists('staff');
  28.    if (!Schema::hasTable('staff')) {
  29.        Schema::create('staff', function (Blueprint $table) {
  30.            $table->id();
  31.            $table->string('name');
  32.            $table->string('email')->unique();
  33.            $table->string('dept');        
  34.            $table->string('bran');            
  35.        });
  36.         DB::insert('insert into staff (name,email,dept,bran)
  37.        values (?,?,?,?)',
  38.             ['john',
  39.             '[email protected]',
  40.             'D1',
  41.             'D1B1']);  
  42.         DB::insert('insert into staff (name,email,dept,bran)
  43.        values (?,?,?,?)',
  44.             ['nancy',
  45.             '[email protected]',
  46.             'D2',
  47.             'D2B1']);  
  48.    }
  49.  
  50.  
  51.    Schema::dropIfExists('department');
  52.    if (!Schema::hasTable('department')) {
  53.        Schema::create('department', function (Blueprint $table) {
  54.            $table->id();
  55.            $table->string('code')->unique();
  56.            $table->string('name');
  57.        });
  58.         DB::insert('insert into department (code,name)
  59.        values (?,?)',
  60.             ['D1',
  61.             'Department 1']);  
  62.         DB::insert('insert into department (code,name)
  63.        values (?,?)',
  64.             ['D2',
  65.             'Department 2']);        
  66.    }
  67.  
  68.    Schema::dropIfExists('branch');
  69.    if (!Schema::hasTable('branch')) {
  70.        Schema::create('branch', function (Blueprint $table) {
  71.            $table->id();
  72.            $table->string('deptcode');
  73.            $table->string('code')->unique();
  74.            $table->string('name');
  75.        });
  76.         DB::insert('insert into branch (deptcode,code,name)
  77.        values (?,?,?)',
  78.             ['D1',
  79.             'D1B1','Branch 1 of D1']);  
  80.         DB::insert('insert into branch (deptcode,code,name)
  81.        values (?,?,?)',
  82.             ['D1',
  83.             'D1B2','Branch 2 of D1']);  
  84.         DB::insert('insert into branch (deptcode,code,name)
  85.        values (?,?,?)',
  86.             ['D2',
  87.             'D2B1','Branch 1 of D2']);  
  88.         DB::insert('insert into branch (deptcode,code,name)
  89.        values (?,?,?)',
  90.             ['D2',
  91.             'D2B2','Branch 2 of D2']);  
  92.    }
  93.  
  94.  
  95.  
  96.    $json_data = '{"table":["staff","department","branch"],"status":"init"}';
  97.  
  98.  
  99.    $result = json_decode($json_data);
  100.  
  101.  
  102.    return response()->json($result, 201);
  103. });
  104.  
  105.  
  106. /* TESTCHECK : the student table should appear in the list
  107. after the REST init command is called */
  108. Route::get('/show_tables',function(){
  109.     //$tables =  DB::select('SHOW TABLES');
  110.     $tables = DB::select("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
  111.     echo "tables:<br/>";
  112.     foreach($tables as $table){
  113.         $arry =  (array) $table;
  114.         foreach ($arry as $value) {
  115.             echo $value."<br/>";
  116.         }
  117.     }
  118. });
  119.  
  120. /* TESTCHECK: call getall via web browser and REST client */
  121. Route::match(array('GET', 'POST'),'/getall', function () {
  122.     $student = DB::select('select * from student');
  123.     return response()->json($student, 200);
  124. });
  125.  
  126. /* TESTCHECK: call REST GET command via web browser */
  127. Route::get('/insert/{name}/{email}',function($name,$email){
  128.     $timestamp = time();
  129.     DB::insert('insert into student (id, name,email)
  130.        values (?, ?,?)',
  131.         [$timestamp,$name.'_'.$timestamp,$email.'_'.$timestamp]);
  132.     echo "record inserted.<br/>";
  133. });
  134.  
  135.  
  136. /* */
  137. /* TESTCHECK: call the following REST POST commands via REST client */
  138. /* */
  139.  
  140. Route::post('/insert',function(Request $request)
  141.   {
  142.     $payload = json_decode($request->getContent(), true);
  143.     try {
  144.       // Get data here, eg. make an external API request or DB query
  145.       $response = [
  146.         'name' => $payload['name'],
  147.         'email' => $payload['email']
  148.       ];
  149.  
  150.     $timestamp = time();
  151.     DB::insert('insert into student (id, name,email)
  152.        values (?, ?,?)',
  153.         [$timestamp,$response['name'].'_'.$timestamp
  154.         ,$response['email'].'_'.$timestamp]);
  155.  
  156.  
  157.     } catch (\GuzzleHttp\Exception\BadResponseException $e) {
  158.       $errorResJson = $e
  159.         ->getResponse()
  160.         ->getBody()
  161.         ->getContents();
  162.       $errorRes = json_decode(stripslashes($errorResJson), true);
  163.       // Return error
  164.       return response()->json(
  165.         [
  166.           'message' => 'error',
  167.           'data' => '$errorRes'
  168.         ],
  169.         $errorRes['response']['code']
  170.       );
  171.     }
  172.     // Return success
  173.     return response()->json(
  174.       [
  175.         'status' => '200',
  176.         'data' => '$response',
  177.         'message' => 'success'
  178.       ],
  179.       200
  180.     );
  181.   }
  182. );
  183.  
  184. Route::post('/update',function(Request $request)
  185.   {
  186.    $payload = json_decode($request->getContent(), true);
  187.     try {
  188.       $response = [
  189.         'id' => $payload['id'],
  190.         'name' => $payload['name'],
  191.         'email' => $payload['email']
  192.       ];
  193.  
  194.     $affected = DB::update(
  195.     'update student set name = ?, email=? where id = ?',
  196.     [$response['name'],$response['email'],$response['id']]);
  197.  
  198.  
  199.     } catch (\GuzzleHttp\Exception\BadResponseException $e) {
  200.       $errorResJson = $e
  201.         ->getResponse()
  202.         ->getBody()
  203.         ->getContents();
  204.       $errorRes = json_decode(stripslashes($errorResJson), true);
  205.       // Return error
  206.       return response()->json(
  207.         [
  208.           'message' => 'error',
  209.           'data' => '$errorRes'
  210.         ],
  211.         $errorRes['response']['code']
  212.       );
  213.     }
  214.     // Return success
  215.     return response()->json(
  216.       [
  217.         'status' => '200',
  218.         'data' => $affected ,
  219.         'message' => 'success'
  220.       ],
  221.       200
  222.     );
  223.   }
  224. );
  225.  
  226.  
  227. Route::post('/delete',function(Request $request)
  228.   {
  229.    $payload = json_decode($request->getContent(), true);
  230.     try {
  231.       $response = [
  232.         'id' => $payload['id']
  233.       ];
  234.  
  235.     $deleted = DB::delete('delete from student where id = ?',
  236.     [$response['id']]);
  237.  
  238.  
  239.     } catch (\GuzzleHttp\Exception\BadResponseException $e) {
  240.       $errorResJson = $e
  241.         ->getResponse()
  242.         ->getBody()
  243.         ->getContents();
  244.       $errorRes = json_decode(stripslashes($errorResJson), true);
  245.       // Return error
  246.       return response()->json(
  247.         [
  248.           'message' => 'error',
  249.           'data' => '$errorRes'
  250.         ],
  251.         $errorRes['response']['code']
  252.       );
  253.     }
  254.     // Return success
  255.     return response()->json(
  256.       [
  257.         'status' => '200',
  258.         'data' => $deleted ,
  259.         'message' => 'success'
  260.       ],
  261.       200
  262.     );
  263.   }
  264. );
  265.  
Tags: laravel8
Advertisement
Add Comment
Please, Sign In to add comment