How to Automatically Login into Laravel App in Your Local Dev Environment
I often find myself spinning up Laravel projects for prototypes and idea testing and then letting them sit until I can pick them back up. Logging in whenever I start work gets annoying, and there’s no point in manually logging in to my local instance since my account is the admin. Fortunately, there are a few solutions to automate this process in Laravel. I’ll delve into the various methods to automatically log in to your Laravel app in your local development environment, enhancing your workflow and boosting productivity.
Utilizing session-based auto-login:
One approach to automating the login process for the Laravel application is session-based auto-login. This method involves setting up a mechanism that automatically logs in a predefined user whenever the application is accessed in the local development environment.
Each solution below assumes you’ve seeded or registered a local user account in your database.
1. Creating a custom route for auto-login:
You can create a custom route in your Laravel routes file (routes/web.php
) that triggers the auto-login functionality.
// routes/web.php
Route::get('/auto-login', function () {
$user = App\Models\User::find(1); // Fetch the user you want to auto-login
Auth::login($user);
return redirect('/dashboard'); // Redirect to a specific page after login
});
2. Implementing auto-login logic:
When you access the /auto-login
route in your local development environment, Laravel will automatically log in the specified user, redirecting them to the desired page (in this case, /dashboard
).
Leveraging custom middleware for auto-login:
Another method to automate your Laravel application’s login process is leveraging custom middleware designed for auto-login functionality. This approach provides more flexibility and control over the auto-login process, allowing you to define custom logic and conditions for authentication.
1. Creating a custom middleware for auto-login:
Generate a new middleware using the Artisan command make:middleware
.
php artisan make:middleware AutoLoginMiddleware
2. Registering the middleware in Laravel:
Register the custom middleware in the HTTP kernel (app/Http/Kernel.php
) to apply it to the desired routes or groups of routes.
// app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// Other middleware...
\App\Http\Middleware\AutoLoginMiddleware::class,
],
];
Registering in the Boot method in AppServiceProvider:
This method allows you to log in automatically as soon as you load the application, and it is the method I use most often. I added a check to ensure that the environment is local.
if ($this->app->environment(‘local’)) {
$user = User::first();
if (isset($user)) {
$this->app[‘auth’]->setUser(User::first());
}
}
7-22-2024 – Update for the Boot method in AppService Provider
If you don’t have the user table seeded with a user, the above code will cause an error when running the seeders. I tweaked the code to check for the table’s existence to avoid the error when running seeders.
if ($this->app->environment('local') && \Illuminate\Support\Facades\Schema::hasTable('users')) {
$user = User::first();
if (isset($user)) {
$this->app['auth']->setUser(User::first());
}
}
Bonus: Generating a seeder for the Users table
Sometimes, you might want to seed your database with an admin user for testing purposes. Here’s how you can do it:
A. Creating a UserSeeder class:
Generate a new seeder class using the Artisan command make:seeder
.
php artisan make:seeder UserSeeder
B. Seeding the database with an admin user:
Within the generated UserSeeder
class, define the logic to create an admin user.
// database/seeders/UserSeeder.php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
class UserSeeder extends Seeder
{
public function run()
{
User::create([
'name' => 'Admin',
'email' => 'admin@example.com',
'password' => Hash::make('password'), // Change this to something more secure
// Additional user data...
]);
}
}
Finally, run the seeder using the Artisan command db:seed
.
php artisan db:seed --class=UserSeeder
Following these steps, you can seamlessly integrate auto-login functionality into your Laravel application’s local development environment, reducing the time and effort spent on repetitive login tasks. Additionally, seeding your database with an admin user ensures that you have a user account available for testing and development purposes.
How to use Backblaze B2 with Laravel
I am working on a Laravel project and decided to use a Backblaze bucket as it’s cheaper for storage when compared to AWS S3. I couldn’t find a tutorial on how to get it working from scratch and I tested a bunch of Laravel B2 libraries that didn’t end up working. The good news is that you don’t need a special B2 plugin and instead can use the S3 package recommended by the Laravel docs.
If you haven’t added the flysystem-aws-s3 package, add it to your project using composer:
composer require league/flysystem-aws-s3-v3
Login to your B2 account and create your bucket with your required settings. Once created, you’ll want to create a new application key with the permissions you need for your app. You should get a confirmation once it’s generated:
Open your .env file and locate the settings for AWS. You’ll need to add one key that’s not there by default:
AWS_ENDPOINT=
Match the settings in your .env from the application key to the values below.
AWS_ACCESS_KEY_ID=keyID
AWS_SECRET_ACCESS_KEY=applicationKey
AWS_DEFAULT_REGION=us-west-000
AWS_BUCKET=bucket-name
AWS_ENDPOINT=S3 Endpoint
Now you should be able to call the Laravel storage system like normal:
\Storage::disk('s3')->put('test.txt', 'test');
How to Extract Text from image using Laravel and Amazon Rekognition API
I’m currently working on a project that requires extracting text from images of variable quality. I’m doing quick prototypes using PHP and Laravel, but I’ve found the documentation for accomplishing this a bit lacking. After working on it for a bit, I figured out a really simple solution and am sharing in case it helps anyone else.
This sample will send the image to the API as a blob instead of using a URL. I had tried Base64 encoding it without any luck. I discovered that using Imagick was the easiest way to make this work so the sample relies on that.
Fire up terminal and add a requirement for aws/aws-sdk-php:
composer require aws/aws-sdk-php
Add keys for your AWS access keys and region to your .ENV file:
AWS_REGION=YOUR_REGION
AWS_SECRET_ACCESS_KEY=ENTER_YOUR_KEY
AWS_ACCESS_KEY_ID=ENTER_YOUR_KEY
Create a controller, add the snippet below, and create a route to the controller. Check the URL and you should have a dump showing the array returned from AWS with all the text, bounding boxes, and information.
//Build config array for AWS variables
$config = array(
'region' => env('AWS_REGION'),
'version' => 'latest',
'credentials' => array(
'key' => env('AWS_KEY'),
'secret' => env('AWS_SECRET')
)
);
//Replace with path to image or uploaded image.
$path = '{path to image.jpg}';
$image = new Imagick($path);
$imdata = $image->getImageBlob();
$client = new RekognitionClient($config);
$result = $client->detectText([
'Image' => ['Bytes' => $imdata],
]);
//Dump Result
dd($result);
How to test email sending in Laravel 5.3 using artisan tinker
I’m building a Laravel app and ran into an error when trying to send mail but wasn’t getting an error back since the request was posted through ajax. If you’re trying to troubleshoot it, artisan tinker app is very useful to get more information on the error.
Fire up terminal/command line and run:
php artisan tinker
and then run the following snippet:
\Mail::raw('hello world', function($message) {
$message->subject('Testing email')->to('test@example.org');
});
You should either see a success/null message if everything was correct, or an error with details on what went wrong.
The error I encountered required configuring 2FA in Gmail or you can choose setting the insecure app option up to send through Gmail for testing.