Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Last active October 23, 2023 07:19
Show Gist options
  • Save nasrulhazim/25948dbf1f3a7d378bb5fe0463b49578 to your computer and use it in GitHub Desktop.
Save nasrulhazim/25948dbf1f3a7d378bb5fe0463b49578 to your computer and use it in GitHub Desktop.
Laravel Default API Login

Setup

Migration

Create new migration script:

php artisan make:migration add_api_token --table=users

Open up the migration script just created and add the following:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class AddApiToken extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->char('api_token', 60)->nullable()->after('password');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('api_token');
        });
    }
}

Then do the migration:

php artisan migrate

Model

Update the app/User.php $fillable property:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'api_token',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Login & Logout Route

Next, setup a simple route to login & logout form API endpoints:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
 */
 
/* Setup CORS */
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

// Route::post('login', 'Auth\LoginController@ApiLogin');
Route::post('login', function (Request $request) {
    
    if (auth()->attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
        // Authentication passed...
        $user = auth()->user();
        $user->api_token = str_random(60);
        $user->save();
        return $user;
    }
    
    return response()->json([
        'error' => 'Unauthenticated user',
        'code' => 401,
    ], 401);
});

Route::middleware('auth:api')->post('logout', function (Request $request) {
    
    if (auth()->user()) {
        $user = auth()->user();
        $user->api_token = null; // clear api token
        $user->save();

        return response()->json([
            'message' => 'Thank you for using our application',
        ]);
    }
    
    return response()->json([
        'error' => 'Unable to logout user',
        'code' => 401,
    ], 401);
});

Test

Use Postman to test:

Login

  • API Endpoint: http://domain/api/login
  • HTTP Method: POST
  • Headers: Accept: application/json
  • Body
    • email [your-login]
    • password [your-password]
  • Response: You should receive your details

Logout

  • API Endpoint: http://domain/api/logout
  • HTTP Method: POST
  • Headers:
    • Accept: application/json
    • `Authorization: Bearer [login-token]
  • Body
    • email [your-login]
    • password [your-password]
  • Reponse: You should receive logout message
@CyberPunkCodes
Copy link

@embashgit i would love to know how to twerk api too

Lol

lolling your lol... and at @embashgit almost 3 years later

🤣

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment