Monday, April 10, 2023

[phpsandbox][laravel][api] auth, dev and common cotroller for api service with sanctum

 .

(0) Create a phpsandbox account

Surf to https://phpsandbox.io

Create an account e.g. using Google account. 


(1) Create PHP Laravel Project

Select Laravel version e.g. Laravel 8

Type a name e.g. lara8


(2) Configure Database

In config/database.php edit as follows:

    |--------------------------------------------------------------------------

    | Default Database Connection Name

    |--------------------------------------------------------------------------

        'default' => env('DB_CONNECTION', 'sqlite'),

    |--------------------------------------------------------------------------

    | Database Connections

    |--------------------------------------------------------------------------

        'sqlite' => [

            'driver' => 'sqlite',

            'url' => env('DATABASE_URL'),

            'database' => database_path('database.sqlite'),

            'prefix' => '',

            'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),

        ],


(3) Migrate Project Database

php artisan migrate



(4) Edit API script file

(routes/api.php)

<?php


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DevController;

use App\Http\Controllers\AuthController;

use App\Http\Controllers\CommonController;


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {

    return $request->user();

});


/* hello */

Route::get('/hello', function () {

    return( 'hello');

});


/* auth */

Route::post('/register',[AuthController::class,'register']);

Route::post('/login',[AuthController::class,'login']);

Route::post('/me',[AuthController::class,'me'])->middleware('auth:sanctum');


/* dev */

Route::get('/init',[DevController::class,'init']);

Route::get('/table',[DevController::class,'get_table']);

Route::get('/{table}/desc',[DevController::class,'get_table_description']);


/* common */

Route::get('/{table}/record',[CommonController::class,'get_table_record']);

Route::get('/{table}/{record_where}/{field}/{value}',[CommonController::class,'get_table_record_where'])

->where(['record_where' =>'record_where|recordw']);


Route::get('/insert/{json?}',[CommonController::class,'get_insert_record']);

Route::post('/insert',[CommonController::class,'post_insert_record']);


Route::get('/update/{json?}',[CommonController::class,'get_update_record']);

Route::post('/update',[CommonController::class,'post_update_record']);


Route::get('/delete/{json?}',[CommonController::class,'get_delete_record']);

Route::post('/delete',[CommonController::class,'post_delete_record']);


(5) Edit DevController script file

(app/Http/Controllers/DevController.php)

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use Illuminate\Support\Facades\DB;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;


class DevController extends Controller

{

    public function init(Request $request)

    {

        Schema::dropIfExists('staff');        

        if (!Schema::hasTable("staff")) {

            Schema::create("staff", function (Blueprint $table) {

                $table->id();

                $table->string("s_name");

                $table->string("s_email")->unique();

                $table->string("s_dept");

                $table->string("s_bran");

            });

        }

        if (Schema::hasTable("staff")) {

            DB::delete('delete from staff');

            DB::insert('insert into staff (s_name,s_email,s_dept,s_bran) 

            values (?,?,?,?)',

            ['john','john@gmail.com','D1','D1B1']);

            DB::insert('insert into staff (s_name,s_email,s_dept,s_bran) 

            values (?,?,?,?)',

            ['nancy','nancygmail.com','D2','D2B2']);

        }

        Schema::dropIfExists('dept');        

        if (!Schema::hasTable("dept")) {

            Schema::create('dept', function (Blueprint $table) {

                $table->id();

                $table->string('s_code')->unique();  

                $table->string('s_name');            

            });

        }

        if (Schema::hasTable("dept")) {

            DB::delete('delete from dept');

            DB::insert('insert into dept (s_code,s_name) values (?,?)', 

            ['D1','Department 1']);   

            DB::insert('insert into dept (s_code,s_name) values (?,?)', 

            ['D2','Department 2']);   

        }

        Schema::dropIfExists('bran');

        if (!Schema::hasTable("bran")) {

            Schema::create('bran', function (Blueprint $table) {

                $table->id();

                $table->string('s_code')->unique();  

                $table->string('s_dept');                    

                $table->string('s_name');            

            });

        }

        if (Schema::hasTable("bran")) {

            DB::delete('delete from bran');

            DB::insert('insert into bran (s_dept,s_code,s_name) 

            values (?,?,?)', 

            ['D1','D1B1','Branch 1 of D1']);   

            DB::insert('insert into bran (s_dept,s_code,s_name) 

            values (?,?,?)', 

            ['D1','D1B2','Branch 2 of D1']);   

            DB::insert('insert into bran (s_dept,s_code,s_name) 

            values (?,?,?)', 

            ['D2','D2B1','Branch 1 of D2']);   

            DB::insert('insert into bran (s_dept,s_code,s_name) 

            values (?,?,?)', 

            ['D2','D2B2','Branch 2 of D2']);    

        }           

        

        /*create json data*/

        $json_data =

            '{"table":["staff","dept","bran"],"status":"init"}';

        /*convert json object to php object*/

        $response = json_decode($json_data);

        /**/

        return response()->json($response, 200);

    }


    public function get_table()

    {    

        /*mysql*/

        //$table_collection =  DB::select('SHOW TABLES'); 

        /*sqlite*/

        $table_collection = DB::select("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");

        return response()->json($table_collection, 200);

    }    


     public function get_table_description($table)

    {    

        $field_collection = Schema::getColumnListing($table);

        return response()->json($field_collection, 200);

    }      

    

    

    

    

}


(6) Edit CommonController script file

(app/Http/Controllers/CommonController.php)

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use Illuminate\Support\Facades\DB;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;


class CommonController extends Controller

{

    public function get_table_record($table)

    {

        $result = DB::select("select * from " . $table);

        return response()->json($result, 200);

    }

    public function get_table_record_where($table,$recordw,$field,$value)

    {

        $result = DB::select('select * from ' . $table . ' where ' .

        $field . ' = ' . $value);

        return response()->json($result, 200);

    }    



 


    public function exec_insert_record($objt_param)

    {

        $response = (object) ['result' => (object)[],'error' => (object)[]];

        

        /*entity(e) prop exist in input parameter object*/

        if (isset($objt_param->e)) {

            

            $entity=$objt_param->e;

            /*entity table exist in schema*/

            if (Schema::hasTable($entity)) {

                try { 

                /*get field names */

                $arry_field= Schema::getColumnListing($entity);

                /*remove id field*/

                array_shift($arry_field);

                /*prep part1.1: insert into field*/

                $strg_sql='insert into '.$entity.'('.implode(",", 

                    $arry_field).')';

                /*prep part1.2: field format*/

                $strg_sql.=' values ('.implode(",",

                    array_map(function($v){return '?';},$arry_field)).')';

                /*prep part2: field values*/

                $objt_reco=$objt_param->reco;

                $arry_value=array();

                foreach ($arry_field as $field) {

                    if(isset($objt_reco[$field])){

                        array_push($arry_value,$objt_reco[$field]);

                    }else{

                        array_push($arry_value,null);

                    }

                }

                $response->result=DB::insert($strg_sql,$arry_value); 

                }

    

                catch(\Illuminate\Database\QueryException $ex){

                    $response->error=$ex->getMessage();

                } 

                catch (ModelNotFoundException $ex) {

                    $response->error=$ex->getMessage();

                }  


            }/* if table exist */

        }/* if prop exist */

        return response()->json($response, 200);

    }

    

    public function get_insert_record($json=null)

    {

        $objt_param = (object) json_decode($json, true);

        return $this->exec_insert_record($objt_param);

    }   

    public function post_insert_record(Request $request)

    {

        return $this->exec_insert_record($request);

    }   



    public function exec_update_record($objt_param)

    {

        $response = (object) ['result' => (object)[],'error' => (object)[]];

        

        /*entity(e) prop exist in input parameter object*/

        if (isset($objt_param->e)) {

            

            $entity=$objt_param->e;

            /*entity table exist in schema*/

            if (Schema::hasTable($entity)) {

                try { 

                /*get field names */

                $arry_field= Schema::getColumnListing($entity);

                /*remove id field*/

                array_shift($arry_field);

                /*prep part1: update ... set*/

                $strg_sql='update '.$entity.' set ';

                /*prep part2: field mask, field value*/

                $objt_reco=$objt_param->reco;

                $arry_mask=array();

                $arry_value=array();

                foreach ($arry_field as $field) {

                    array_push($arry_mask,$field.'=?');

                    array_push($arry_value,$objt_reco[$field]);

                }

                $strg_sql.= implode(",",$arry_mask);

                /*prep part3: where*/

                $strg_sql.=' where id = ?';

                array_push($arry_value,$objt_reco['id']);

                $response->result=DB::insert($strg_sql,$arry_value); 

                }

    

                catch(\Illuminate\Database\QueryException $ex){

                    $response->error=$ex->getMessage();

                } 

                catch (ModelNotFoundException $ex) {

                    $response->error=$ex->getMessage();

                }  


            }/* if table exist */

        }/* if prop exist */

        return response()->json($response, 200);

    }


    public function get_update_record($json=null)

    {

        $objt_param = (object) json_decode($json, true);

        return $this->exec_update_record($objt_param);

    }   

    public function post_update_record(Request $request)

    {

        return $this->exec_post_record($request);

    } 



    public function exec_delete_record($objt_param)

    {

        $response = (object) ['result' => (object)[],'error' => (object)[]];

        

        /*entity(e) prop exist in input parameter object*/

        if (isset($objt_param->e)) {

            

            $entity=$objt_param->e;

            /*entity table exist in schema*/

            if (Schema::hasTable($entity)) {

                try { 

                /*prep part1: delete from*/

                $strg_sql='delete from '.$entity;

                /*prep part2: where*/

                $strg_sql.=' where id = '.$objt_param->id;

                $response->result=DB::delete($strg_sql); 

                }

    

                catch(\Illuminate\Database\QueryException $ex){

                    $response->error=$ex->getMessage();

                } 

                catch (ModelNotFoundException $ex) {

                    $response->error=$ex->getMessage();

                }  


            }/* if table exist */

        }/* if prop exist */

        return response()->json($response, 200);

    }


    public function get_delete_record($json=null)

    {

        $objt_param = (object) json_decode($json, true);

        return $this->exec_delete_record($objt_param);

    }   

    public function post_delete_record(Request $request)

    {

        return $this->exec_delete_record($request);

    } 

    

}



(7) Edit AuthController script file

(app/Http/Controllers/AuthController.php)

<?php


namespace App\Http\Controllers;


use App\Models\User;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Hash;


class AuthController extends Controller

{

    public function register(Request $request)

    {

        

        $validatedData = $request->validate([

            'name' => 'required|string|max:255',

            'email' => 'required|string|email|max:255|unique:users',

            'password' => 'required|string|min:8',

        ]);


        $user = User::create([

            'name' => $validatedData['name'],

            'email' => $validatedData['email'],

            'password' => Hash::make($validatedData['password']),

        ]);


        $token = $user->createToken('auth_token')->plainTextToken;


        return response()->json([

            'access_token' => $token,

            'token_type' => 'Bearer',

        ]);

    }


    public function login(Request $request)

    {

        if (!Auth::attempt($request->only('email', 'password'))) {

            return response()->json([

                'message' => 'Invalid login details'

            ], 401);

        }


        $user = User::where('email', $request['email'])->firstOrFail();


        $token = $user->createToken('auth_token')->plainTextToken;


        return response()->json([

            'access_token' => $token,

            'token_type' => 'Bearer',

        ]);

    }


    public function me(Request $request)

    {

        return $request->user();

    }

}



.




No comments:

Post a Comment