Sunday, April 9, 2023

[phpsandbox][laravel][web] quick setup laravel Sanctum API service

  .

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. lara8api


(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 database

in console window, run command

php artisan migrate

create and run web script to view the created tables.


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

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

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

    foreach($tables as $table){

        $arry =  (array) $table;

        foreach ($arry as $value) {

            echo $value."<br/>";

        }

    }

});


.

(4) Create AuthController

Run console command:

php artisan make:controller AuthController


Edit App\Http\Controllers\AuthController.php

.

<?php


namespace App\Http\Controllers;


use App\Models\User;

use Illuminate\Http\Request;

use Illuminate\Http\Response;

use Illuminate\Support\Facades\Hash;


class AuthController extends Controller

{

    public function sign_up(Request $request){

        $data = $request->validate([

            'name' => 'required|string',

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

            'password' => 'required|string|confirmed'

        ]);


        $user = User::create([

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

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

            'password' => bcrypt($data['password'])

        ]);


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


        $res = [

            'user' => $user,

            'token' => $token

        ];

        return response($res, 201);

    }


    public function login(Request $request)

    {

        $data = $request->validate([

            'email' => 'required|string',

            'password' => 'required|string'

        ]);


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


if (!$user || !Hash::check($data['password'], $user->password)) {

            return response([

                'msg' => 'incorrect username or password'

            ], 401);

        }


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


        $res = [

            'user' => $user,

            'token' => $token

        ];


        return response($res, 201);

    }



}



.

(5) Update API script

.

<?php


use Illuminate\Http\Request;

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\AuthController;

use App\Http\Controllers\PostController;

/*

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

| API Routes

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

|

| Here is where you can register API routes for your application. These

| routes are loaded by the RouteServiceProvider and all of them will

| be assigned to the "api" middleware group. Make something great!

|

*/


#single middleware routing

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

    return $request->user();

});


#group middleware routing

Route::group(['middleware' => ['auth:sanctum']], function () {

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

        $student = DB::select('select * from users');

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

    });

});


#public routing

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


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


Route::post('login', [ 'as' => 'login', 'uses' => 'AuthController@do']);


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

        return response([

            'error' => 'not logged in'

        ]);

});


.

No comments:

Post a Comment