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

November 3, 2021 · 2 min · 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....

November 2, 2021 · 2 min · 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 · 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....

October 21, 2021 · 1 min · 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' => '', '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....

October 17, 2021 · 1 min · Saqib Razzaq