How to setup token API auth with Sanctum in Laravel

Read about Laravel Sanctum Create your laravel project composer create-project --prefer-dist laravel/laravel my-laravel-blog-api Move into project directory and then install Sanctum composer require laravel/sanctum Now let’s publish migrations and configuration files php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" Run database migrations php artisan migrate Make sure your User model looks like this use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; } Make an authentication / user controller. Let’s use AuthenticationController for this php artisan make:controller AuthenticationController Then add following code in this controller se Illuminate\Support\Facades\Hash; 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', ]); } First, we validate the incoming request to make sure all required variables are present. Then we persist the supplied details into the database. Once a user has been created, we create a new personal access token for them using the createToken() method and give the token a name of auth_token. Because createToken() will return an instance of Laravel\Sanctum\NewAccessToken, we call the plainTextTokenproperty on the instance to access the plain-text value of the token. Finally, we return a JSON response containing the generated token as well as the type of the token. Then add login method to your controller. It should look like this use App\Models\User; use Illuminate\Support\Facades\Auth; 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', ]); } Add following two routes to allow registrations and login Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']);

November 3, 2021 · 2 min · 287 words · Saqib Razzaq

How to test Registration and Login in Laravel

I often work with Laravel APIs that require user registration and authentication. Of course, there is no stability in building applications without unit tests. Hence, I create following tests to ensure registration and login functions are working as expected. TestRegister.php Run php artisan make:test TestRegister Go to tests\Feature and open TestRegister.php Use following test to make sure user registrations are working. Of course, this is a minimal example. But this should give you a good idea of how you can get started. public function testsRegistration() { $payload = [ 'name' => 'Jenny', 'email' => 'jenny@test.com', 'password' => 'password', 'level' => '5', ]; $this->json('post', '/api/register', $payload) ->assertStatus(201) ->assertJsonStructure([ 'data' => [ 'access_token', 'token_type', ], ]);; } You’ll need to ajdust $payload variables according to what your API’s register endpoint expects. You’ll also need to adjust assertJsonStructure values based on what you are sending back as response. ...

November 2, 2021 · 2 min · 292 words · Saqib Razzaq

Laravel - manually handle HTTP exceptions

Laravel automatically handles HTTP exceptions and throws errors / redirects as it sees fit. Sometimes, this isn’t an ideal behaviour. I was building an API and wanted to display custom messages for missing routes, forbidden and other errors. This can be done like this Open app\Exceptions\Handler.php If you want to handle missing models, paste following snippet in render method if ($exception instanceof ModelNotFoundException) { return response()->json([ 'error' => 'Model not found' ], 404); } If you’d like to handle other HTTP exceptions, paste the following snippet instead if ($this->isHttpException($exception)) { switch ($exception->getStatusCode()) { // not authorized case '403': return \Response::json([ 'error' => 'You are not allowed to access this' ], 403); break; // not found case '404': return \Response::json([ 'error' => 'Resource not found' ], 404); break; // internal error case '500': return \Response::json([ 'error' => 'Something went terribly wrong' ], 500); break; default: return $this->renderHttpException($exception); break; } }

November 2, 2021 · 1 min · 149 words · Saqib Razzaq

How to create a user by default in Laravel

Sure, we can user Laravel’s database seeding and $faker to create any number of fake users. Personally, I don’t like to waste time fetching a new random user and their email address to continue my testing. I like have the same user created each time database is seeded. I do it like this. Run below command to create a new seeder in database/seeds directory. php artisan make:seeder UserSeeder In run method of UserSeeder.php paste following code $user = User::create([ 'name' => 'Saqib', 'email' => 'saqib@saqib.com', 'password' => Hash::make('password'), 'level' => 1 ]); Finally, add below line in run method in seeds\DatabaseSeeder.php $this->call(UserSeeder::class); ...

October 21, 2021 · 1 min · 125 words · Saqib Razzaq

How to create and use Seeders in Laravel

Create a seeder php artisan make:seeder seederName This creates a file seederName in database/seeds You can use a model or default database class. I’ll show you both examples To use an existing model, try this approach // assumes you've already added "use App\User" and "use Illuminate\Support\Facades\Hash;" at top of your file $user = User::create([ 'name' => 'Saqib', 'email' => 'saqib@saqib.com', 'password' => Hash::make('password'), 'level' => 1 ]); If you don’t have a model and want to run database inserts, try something like this DB::table('users')->insert([ 'name' => 'Jon Snow', 'email' => 'saqib@test.com', 'password' => Hash::make('password') ]); Run php artisan db:seed or php artisan migrate:fresh --seed to run seeders

October 17, 2021 · 1 min · 107 words · Saqib Razzaq

The common Laravel template structure

First, create a file that defines the structure of your page layout.blade.php @include('includes.header') @yield('content') @include('includes.footer') Then create files that yield content index.blade.php @extends('common_template') @section('content') {{$data['title']}} @endsection

October 17, 2021 · 1 min · 26 words · Saqib Razzaq

Laravel - create a user by default

Sure, we can user Laravel’s database seeding and $faker to create any number of fake users. Personally, I don’t like to waste time fetching a new random user and their email address to continue my testing. I like have the same user created each time database is seeded. I do it like this. Run below command to create a new seeder in database/seeds directory. php artisan make:seeder UserSeeder In run method of UserSeeder.php paste following code $user = User::create([ 'name' => 'Saqib', 'email' => 'saqib@saqib.com', 'password' => Hash::make('password'), 'level' => 1 ]); Finally, add below line in run method in seeds\DatabaseSeeder.php $this->call(UserSeeder::class); ...

September 17, 2021 · 1 min · 125 words · Saqib Razzaq

How to modify Laravel 'HOME' redirection path

When a user logs in, Laravel redirects it to path stored in HOME constant by default. If you want to modify this constant or add constants of your own, you can do it like this. Open app\Providers\RouteServiceProvider.php Search public const HOME to update HOME constant You can add your own just like that

August 19, 2021 · 1 min · 53 words · Saqib Razzaq

Laravel - common template structure

First, create a file that defines the structure of your page layout.blade.php @include('includes.header') @yield('content') @include('includes.footer') Then create files that yield content index.blade.php @extends('common_template') @section('content') {{$data['title']}} @endsection

August 19, 2021 · 1 min · 26 words · Saqib Razzaq

Bootstrap Auth Scaffholding in Laravel

If Laravel is not installed, first run composer create-project laravel/laravel composer require laravel/ui php artisan ui bootstrap --auth

March 17, 2021 · 1 min · 18 words · Saqib Razzaq

How to add a user middleware in Laravel

I was building an API. I had already used auth:api middleware. I was sure that a user was logged in. However, I wanted to protect some of my routes further by only allowing an admin to access them. I was using level field in users table. A level 1 meant it was an admin. Hence, I created an Admin middleware to do what I had in mind. Here is how it can be done. ...

March 17, 2021 · 1 min · 153 words · Saqib Razzaq

How to add helper files in Laravel

There are some cases when you need to add your own custom functions in Laravel. I often have my own custom helpers for speeding up development. You can easily add your own files by following this quick guide. Create a folder in app\Http folder. Let’s assume you created Helpers You can place any number of php files in this directory. Then open composer.json found in your root directory and find "autoload-dev": { "psr-4": { "Tests\\": "tests/" } } Then replace it so it looks like this "autoload-dev": { "psr-4": { "Tests\\": "tests/" }, "files": [ "app/Helpers/filename.php" ] } Finally, run composer dump-autoload and you are good to go

March 17, 2021 · 1 min · 108 words · Saqib Razzaq

How to create model, controller and migration in same command

Follow command can be used to create all three in one line php artisan make:model Modelname -mcr

March 17, 2021 · 1 min · 17 words · Saqib Razzaq

How to fix key is too long error in Laravel

If you are using sublime text run: Ctrl + P: AppServiceProvider.php Then at start of file paste use Illuminate\Support\Facades\Schema; Paste following code in boot() function Schema::defaultStringLength(191);

March 17, 2021 · 1 min · 26 words · Saqib Razzaq

How to migrate and seed with same command

You can run the migrations and seeders in the same line like this php artisan migrate:fresh --seed

March 17, 2021 · 1 min · 17 words · Saqib Razzaq

How to use Refresh database in Laravel PHPUnit Tests

A Laravel project ideally has many tests depending on the size of the project. We don’t want one test’s results to impact others. This is where RefreshDatabase trait comes in handy. It resets database after each test to make sure you get the clean slate for your next test. You can use it like this. First, paste this at top of your test file use Illuminate\Foundation\Testing\RefreshDatabase; Then right after opening { of your test class, paste following use RefreshDatabase; ...

March 17, 2021 · 1 min · 79 words · Saqib Razzaq

How to use validator and get all errors in Laravel

Laravel has a validated function which runs your defined rules and automatically sends errors to your view. This is awesome for most projects but sometimes you may want to handle / read these errors yourself. Or maybe just do it before sending them to view. Here is how you can do that. First of all, add validator at top of your file use Illuminate\Support\Facades\Validator; Then create validator with your rules like this $validator = Validator::make($requestData, [ 'user_id' => ['required', 'integer'] ]); Then use following snippet to get errors as array if ($validator->fails()) { $fieldsWithErrors = $validator->messages()->get('*'); // do anything here }

February 11, 2021 · 1 min · 101 words · Saqib Razzaq

Markdown Syntax Guide

This article offers a sample of basic Markdown syntax that can be used in Hugo content files, also it shows whether basic HTML elements are decorated with CSS in a Hugo theme. ...

March 11, 2019 · 3 min · 446 words · Hugo Authors