Laravel Socialite with socialite-ui

In a previous post, I explained how to install the third party (socialite-ui) on your website, which itself was written to help people with the “Gradually migrating to Laravel” post, but it seems it is not enough, so here is how to fully get socialite working, much of the work is outside your website though, and i won’t be covering that, all you need to do is ask google, for example, how do i enable social logins with google or facebook etc…

The redirect problem

After registering or logging in, your user will be redirected to an absolutely empty “/dashboard“, which is already handled by myrouter.php

Email verification

Before doing anything, let us check that email is working using your SMTP credentials

Create the following route for testing

use Illuminate\Support\Facades\Mail;

Route::get('/test-email', function () {
Mail::raw('This is a test email.', function ($message) {
$message->to('test@example.com')
->subject('Test Email');
});
return 'Email sent!';
});

socialite-ui does not come with email verification (during registration) by default, you will need to enable it, this is simply by following the instructions here

now edit the file (/config/socialite-ui.php) to enable the social logins you want enabled, and alter the other settings as per the page her (https://github.com/Laravel-Uis/socialite-ui)

php artisan config:clear
php artisan cache:clear

installing Laravel 12 with social login

Normally this would not have been worthy of a blog post of its own, there are plenty of posts that explain how to do this, but because I don’t want the post on “Gradually migrating to laravel” to be too long, I have decided to move the part on how to setup a vanilla install of laravel to its own post.

Rather than having you setup sociallite in laravel, there is an amazing starter kit on github (https://github.com/Laravel-Uis/socialite-ui) that we will be using to hit the ground running, this is not an official starter kit, it is by a third party, namely Joel Butcher, the same person behind the good old, now unmaintained socialstream (Socialite and JetStream)

So, let’s get down to business, I assume you have a debian machine up and running

apt install php-fpm nginx libnginx-mod-http-headers-more-filter openssl
apt install php-{dev,common,xml,tokenizer,zip,mysql,curl,mbstring,mysql,opcache,gd,intl,json,xsl,bcmath,imap,soap,readline,sqlite3,gmp,guzzlehttp-guzzle}

Now, make sure the following PHP extensions are enabled (i am pretty sure they are after the commands above) but to be safe, check in php.ini

extension=fileinfo
extension=mbstring
extension=openssl

Remember to “mariadb-secure-installation”, then create a username and database in mysql for laravel ! you can either use PHPMYADMIN or from the command line, makes no difference, remember to flush privileges

Install composer and nodejs

apt install composer nodejs npm
composer --version

Now, I am assuming your web directory is owned by the web server user ! first, install laravel globally, this is a new tool we will use to create laravel installations from now on

su - webdev (Whatever user you want to execute under)
composer global require laravel/installer

Now, add laravel to your path in .bashrc

export PATH="$HOME/.config/composer/vendor/bin:$PATH"
source ~/.bashrc
echo $PATH

IMPORTANT: In my case, all my websites are in folders that follow the patern “/var/www/vhosts/com.websitename.www/public”… hence, i execute the lines below from within the “/var/www/vhosts/” directory ! once i execute the below line, i will have a folder called my-app, I usually rename that to com.websitename.www and there is already a public folder in there, The long and short of this story is, your whole project folder with the public directory inside is creating from the command below, if you do it wrong, you can simply move the files and folders in that folder to where they should be

And now, in your project directory (Which is one level below your public web directory), execute the following, the laravel command is the new way, and if you are not looking for Livewire Volt, just visit the github page to see your 3 other options (Vue, React, and Livewire without volt)

laravel new my-app --using=laravel-uis/socialite-ui-livewire-starter-kit

During the install, it will ask you what testing framework you want, You can pick whatever one you prefer, then it will ask you if you would like to run “npm install and npm run build?”, You can hit no, and run the following command yourself

npm install && npm run build

Configure

Now, edit your .env ! the default one uses sqlite, if you want to use mysql / mariadb (like most PHP people), just make sure this becomes your database in your .env file

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Now, run the following commands

php artisan migrate
The following commands are for reference only
php artisan session:table
php artisan queue:table
php artisan cache:table
php artisan migrate
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear
php artisan migrate:status

Behind Proxy

If you are behind a proxy, you might need to tell laravel 12 to trust proxies… (Edit /bootstrap/app.php), and add the parts

first, add this line at the top

use Illuminate\Http\Request;
$middleware->trustProxies(
//at: '*', // Trust all proxies (use for dynamic/cloud setups like Nginx on the same server; see security notes below)
at: ['127.0.0.1', '192.168.1.0/24', 'xxx.xxx.xxx.xxx'],
headers: Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB // Include if using AWS; optional for standard Nginx
);

Right where there is an empt comment inside

->withMiddleware(function (Middleware $middleware) {

Gradually Migrating a legacy system to Laravel !

This looks long, but it’s simpler than it seems.

Scenario: You have an existing legacy PHP system, and you would like to gradually migrate to Laravel, you don’t want to migrate everything to laravel from the word go (because you either don’t have the time, or you need features from laravel but don’t want to learn laravel all at once, or maybe developing with laravel is your favorite way of learning laravel), whichever it may be, this tutorial is for you.

To get on track, I will assume that all you want for the time being is to have laravel (with socialite) take care of registering and authenticating users, and pass the logged in user data to your system… and leave other migrations for later, this is a good way to get started.

The steps

1- Install Laravel 12

Just a plain old vanilla setup. If you don’t know how to do this, I have the following post for you (Installing laravel 12 with social login), you don’t need to modify anything for this setup to work, yet you might find some stuff that needs some modification (Regardless of this setup), so here are a few modifications you may want to make

all you need now is to make sure you can register as a user, either directly or using social login (Or whatever you want), to speed things up, you might want to use this amazing starter kit here (https://github.com/Laravel-Uis/socialite-ui), bottom line is  a clean Laravel install — nothing fancy..

2- One of the following two options depending on how your system is setup

Option 1– If your system already uses rewrite, have nginx rewrite all your requests to myrouter.php instead of index.php, here is the nginx config file I use, and here is the myrouter.php file

Elaboration: Normally, in a Laravel installation, nginx would rewrite all requests to laravel’s own index.php, what we have done with those two files is have it rewrite it to our own router (myrouter.php), if our existing system knows how to handle the request, it would, if it doesn’t , then it is probably a laravel page that the user is seeking (such as registration page), so we pass control to laravel.

Option 2– If you are not using rewrite in your legacy system, and PHP pages are accessed directly, the laravel recommended nginx config already deals with this since it checks for file existence before rewriting the request to index.php, all you will need to do at this stage is include this small file in your PHP files (require_once rather than include)

3- Integrating the auth system into ours

Our options: What we will do is create an endpoint on Laravel and have our system call it internally

What we won’t do: it is worth mentioning that there are quite a few ways besides the above, but none of them is straight forward, one of them is to include laravel’s internals (the console bootstrap path… what Artisan uses) into our own system, but Laravel’s sessions are serialized and encrypted ( with Illuminate\Encryption\Encrypter and the APP_KEY) so you will have to replicate Laravel’s decryption/unserialization logic,so we will stick to the auth endpoint… and optimize it by only firing it up when needed (To not load laravel for every walk in visitor to the website)

Note: If you will be going by my advice to develop them separately, what comes below needs laravel to function/test/develop, you will need to create a file that checks if laravel is available before firing up, and if not, send back a dummy testing user (or whatever you need), you can make that easier by toggling a “production” flag, and when in production it calls upon laravel, when in development, it serves the dummy user.

3.1 : Create an endpoint in laravel, very simple, Just edit laravel’s routes file ( routes/web.php) and add the following, it is also wrap it in middleware that only allows access from localhost, even though that is not really needed, but keeping security tight is a good idea (You can remove the extra wrapper by deleting everything from ->middleware through the end and putting a semi colon instead, up to you)

Note: I personally added this to /routes/auth.php alongside the login and registration features since it is authentication specific, but technically it makes absolutely no difference

use Illuminate\Support\Facades\Route;

Route::get('/auth/me', function () {
    return response()->json([
        'user' => auth()->check() ? auth()->user() : null,
    ]);
})->middleware(function ($request, $next) {
    if ($request->server->get('SERVER_ADDR') !== $request->ip()) {
        abort(403);
    }
    return $next($request);
});

Now, we need a function to talk to laravel internally and get the user ! we will fire up laravel, take the user data, and go back to our own system

And we also need to know when to call that function, there is no need to fire up Laravel then tear it all down when there is no chance that this might be a logged in user !

Previously, i had a function that fired up laravel internally, but after some digging, I realized that the overhead of calling it over http is very low, and that it will future proof the system (When laravel decide to change things)


function currentUser($http_port) {
    static $cachedUser = null;
    static $resolved = false;

    if (!$resolved) {
        $cachedUser = null; // default

        if (!empty($_COOKIE['voodoo_session'])) {
            //$ch = curl_init("https://www.voodoo.business/auth/me"); // Using your FQDN
            $ch = curl_init("http://127.0.0.1:{$http_port}/auth/me");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5); // optional timeout
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Host: www.voodoo.business',
                'Cookie: voodoo_session=' . $_COOKIE['voodoo_session']
            ]);

            $response = curl_exec($ch);

            if ($response === false) {
                error_log('currentUser cURL error: ' . curl_error($ch));
            } else {
                $data = json_decode($response, true);

                if (json_last_error() !== JSON_ERROR_NONE) {
                    error_log('currentUser JSON decode error: ' . json_last_error_msg());
                } else {
                    $cachedUser = $data['user'] ?? null;
                }
            }

            curl_close($ch);
        }

        $resolved = true;
    }

    return $cachedUser;
}

Now you can simply call the function currentUser as follows, as many times as you wish, it will only invoke laravel once per web request

$user = currentUser();
if ($user) {
    echo "Logged in as {$user['name']}";
} else {
    echo "Not logged in";
}

Improvement – Optimization: You can short circuit earlier by simply connecting to the database and checking if the session id ($sessionId = $_COOKIE[‘laravel_session’];) exists in the database or the file or memory store, then, if it exists, invoke the currentUser function… this will ( check that the session file/row/key exists, not that it’s valid), but getting into this now will complicate the tutorial because there are 3 different scenarios and the solution we are at right now is good enough for most low to medium traffic websites

The logout button

Laravel does not have a page that logs you out as soon as you visit it, this will effectively disable CSRF ! and allow forced logout, so the answer is to create a logout page in Laravel and visit that page, it is very easy

The route file

/routes/web.php

Route::get('/log_me_out', function () {
return view('logout'); // blade template with the button
});

The Blade template

resources/views/logout.blade.php (If you are not familiar with laravel, the part of the file name that is before “.blade.php” is the view name, so the view in the route takes us here

<h1>Click below to log out</h1>

<form method="POST" action="{{ route('logout') }}">
@csrf
<button type="submit">Logout</button>
</form>

All you need to do now is link to /log_me_out, and the user will be presented with the option to logout

Thoughts and ideas

I do not practice what I preach, my projects live inside of each other, the outer project is laravel, and my project lives inside a folder inside laravel (Not inside the public folder, just inside laravel’s project folder), at which point, myrouter.php either reads static files and serves them, or includes php files from my projects folder, so I only have 1 file inside the public folder….

So, in my projects folder, i do the regular steps below

cd /var/www/laravel/innderproject (This is the whole story, running composer inside the project folder)
composer init
composer require nikic/php-parser:^5.6 vlucas/phpdotenv:^5.6

And inside that folder, all files include the code

require __DIR__ . '/vendor/autoload.php';

This loads from the inner vendors folder, laravel knows how to reach the outer one

Trixie… php8.4-imap missing

Error: Unable to locate package php8.4-imap
Error: Couldn’t find any package by glob ‘php8.4-imap’

the debian package maintainer (Ondřej Surý) has released it on his repository, but it is nowhere to be found for Debian 13 on “https://packages.debian.org/“, trixie didn’t trickle down to the website yet, but in SID, it reads “The extension is unbundled from php-src as of PHP 8.4.0.”

I am not yet sure what this means, there is a chance it means we should install it using PECL, I will not do that, I would rather installwith apt, but if i wanted to, i would execute

sudo apt install php-pear php8.4-dev
sudo pecl install imap

There is a chance that it will be coming back to debian’s repositories since Sury (The package maintainer) has it, but I have no idea when

So, let us install it (the IMAP extension and nothing else) from the sury repository to make things simpler when debian has it again

Let us start by adding

sudo apt install -y lsb-release apt-transport-https ca-certificates curl gnupg2
echo "deb https://packages.sury.org/php $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/sury-php.list
curl -fsSL https://packages.sury.org/php/apt.gpg | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/sury-php.gpg
sudo apt update

Now we have added Sury’s repository to apt, let us go ahead and pin it so that only php8.4-imap is sourced from that repo !

sudo tee /etc/apt/preferences.d/sury-php.pref >/dev/null <<'EOF'
Package: *
Pin: release o=deb.sury.org
Pin-Priority: 1

Package: php8.4-imap
Pin: release o=deb.sury.org
Pin-Priority: 990
EOF
sudo apt update

Now install

sudo apt install php8.4-imap

To make sure everything is correct

apt policy php8.4-imap

Now in my case, I need to restart PHP (systemctl restart php8.4), in your case, you might need to restart apache or something else, when in doubt, restart the machine 😛

Once the package is in debian repositories again, we will simply remove /etc/apt/preferences.d/sury-php.pref and /etc/apt/sources.list.d/sury-php.list, then reinstall php8.4-imap.

Can I use Clockwork with codeigniter 3 ?

Yes you can, but not the latest, CodeIgniter support was dropped at one point, but nothing is stopping you from using the old version of clockwork !

Clockwork is maintained by itsgoingd, with the relevant projects here (https://github.com/itsgoingd)

Clockwork’s codeigniter support was dropped with Clockwork 2, but you can still use Clockwork V1.x (Statement from itsgoingD himself here https://github.com/itsgoingd/clockwork/issues/333), Version 1 can be downloaded at (https://github.com/itsgoingd/clockwork/tree/v1), 1.6 seems to be the last V1 published.

But there are a few caveats, for example, what browser extensions work with Clockwork V1.6 ?

Using both Tailwind and Bootstrap 5 in Laravel 9

Here is a scenario, You are using the socialstream laravel plugin by Joel Butcher (You can donate to the guy for his hard work), You don’t have the time to modify the pages, and you want to throw in bootstrap alongside tailwind that ships with socialstream, the process to do this is not so hard, let us stick to this example and resolve the issue and then you can adapt this to whatever your situation is.

Off the bat, bootstrap and tailwind have conflicting class names ! they can not be used together without adding a prefix, but there are solutions to make it happen depending on your use case.

Again, whatever your use case may be, there are multiple solutions that need to be mixed and matched, I will start by providing the methods to allow both Bootstrap and Tailwind to co-exist, then, I will provide the common use cases below and refer to the solution(s) that work best with them

Solution 1- Change the tailwind class prefix !

This is the simplest solution

You start by editing the file tailwind.config.js and adding the prefix option.

module.exports = {
  prefix: 'tw-',
}

The run “npm install && npm run build”

On laravel, this will add tw- as a prefix to all the utility classes, the effect can be seen in the files

the use of tailwind CSS that came with your scaffolding plugins probably is not massive.

Case 1: My design is in bootstrap, but scaffolding packages use tailwind !

For example, one reason you are probably trying to do this is when you have Laravel packages that provide a front end that uses tailwind, but your design is all done in bootstrap !

The solutions are

Laravel Social Login, simple step by step (The whole story)

What is OAuth2

If you are a web developer, you probably understand that OAuth (2) is how you allow your visitors to login to your website using their facebook, twitter, or even github credentials (Too many to name).

The uncontested champion of a plugins to log in users to your website using social networks is Laravel Socialite, (More like register to your website, but you get the idea)

So, to avoid confusion, socialite is the plugin you are looking for, Passport and Sanctum ARE NOT MEANT FOR THIS PURPOSE. here is how they are different

PluginAbout
SocialiteAllows you to easily integrate the option to login to your website with a popular website's credentials
SanctumThe opposite of Socialite, Allows an application to authenticate users using your website as a back-end, usually useful when you create mobile apps for example.
PassportSame concept as Sanctum, but with OAuth2, Unless you need OAuth2, don't use this, Sanctum provides a much simpler API authentication development experience.

Now, let us get to adding social login to our application, socialite.

Laravel development under Linux (Dev Tools)

At this stage, this posst is a stub, I am simply compiling information here then I will come back to edit this

Under linux, the Laravel extensions that i like up to now are

  • Laravel Blade Snippets (For blade templates)
  • PHP namespace resolver (So that we don’t need to look for what namespaces provide for the classes we are using)
  • PHP Intelephense (PHP Autocomplete/intellisense ref finder, etc…)

Laravel 9 on NGINX under Debian 12 (bookworm) – Step by step

This part of the tutorial is a hands on setup to have Laravel working on nginx under Linux. this is not the only way to run Laravel, for all the options, see here

NOTE: Most if not all of the popular development tools are available for Linux and Windows, so If this setup is for development, you might want to install Debian Linux with the Gnome GUI so that you can install the development tools used in the next part of this tutorial, if you are going to be developing on a different machine or this is for production, then you shouldn’t.

STEP 1: Install Debian 11 (Bullseye) on a computer.

STEP 2: Install the basic Laravel environment with the following commands, Laravel 9 requires PHP 8, which at the time of writing is not available in Debian 11 repositories, so we will need to add the repositories from the guy who manages PHP for Debian anyway

sudo apt-get install ca-certificates apt-transport-https software-properties-common gnupg unzip curl
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | tee /etc/apt/sources.list.d/sury-php.list
wget -qO - https://packages.sury.org/php/apt.gpg | apt-key add -
apt-get update

Now, to the actual installation of the environment

apt install php8.1-fpm nginx
apt install php8.1-{dev,common,xml,tokenizer,zip,mysql,curl,mbstring,mysql,opcache,gd,intl,xsl,bcmath,imap,soap,readline,sqlite3,gmp}
apt install redis-server
apt-get install php8.1-redis
apt install mariadb-server mariadb-client

Now you need to secure redis !

Now remember to secure your mariaDB (MySQL) installation with the following command

mysql_secure_installation

Next, we need composer, the PHP dependency manager, to get it execute the following

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer
chmod +x /usr/local/bin/composer
composer --version

The last line above should show you what version of composer you have just installed

Now, remember to never run composer as root, but rather as a regular user, from this point on I am assuming you are running the terminal as a regular user.

I understand that Debian puts the web root in /var/www/html, but i usually like to create a separate directory called /var/vhosts and put all my web projects in it

mkdir /var/vhosts

Now, we need to create a sample project for our learning and training experience

cd /var/vhosts
composer create-project laravel/laravel laraveltestapp
chmod -R 0777 /var/vhosts/laravelapp/storage

Next, We would need to setup nginx to serve this website (“Would like to” actually, because there are alternatives, but I’m keeping it simple), here is an almost standard template for nginx, modify the host name and project name to match your project and preferences.

NGINX vhost config file (In my case /etc/nginx/sites-available/laraveltestapp)

server {
    listen 80;
    listen [::]:80;
    server_name ltest.net www.ltest.net;
    root /var/vhosts/laraveltestapp/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
#	fastcgi_pass unix:/var/run/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Surely for this to work, you will need to add the following two lines to the end of the /etc/hosts file

127.0.0.1 ltest.net
127.0.0.1 www.ltest.net

As soon as we have the file above, we need to create a symbolic link for it in the sites enabled directory

cd /etc/nginx/sites-enabled
ln -s /etc/nginx/sites-available/laraveltestapp

Suddenly, it works through nginx, you should see the welcome page (View) here

Now, to the development environment, how to setup your development environment can be found here

Laravel – Tools and environments

The following are things that are commonly used with Laravel. broken down by category

Environment tools and solutions

  • PHP composer (Mandatory)
  • Docker – Sail (Optional)

Relevant / Compatible server side software

  • Apache2 (2.4) (Web Server)
  • Nginx (Web Server)
  • PHP (PHP8.x for Laravel 9)
  • redis (Data structure store)
  • memcache (in-memory, distributed cache)
  • MeiliSearch (Search application)
  • MailHog (email-testing tool with a fake SMTP server)
  • Selinium (browser automation)
  • MySQL/Mariadb (Database engine, most common)
  • PostgreSQL (Database Engine, very powerful)

Development environments

  • Microsoft Visual Studio Code (Free): built-in support for JavaScript, TypeScript and Node.js, extensions include PHP
  • Sublime text (Not free, works but nags)
  • Apache beans (Free)
  • IntellijIDEA (Not free, one month trial)
  • PHPStorm (Same as IntellijIDEA without the other languages support, Not Free, one month trial)

Database Management

  • MAC: Sequel Pro and sequel ace
  • ALL: PHPMyAdmin, mysql workbench (Oracle),
  • sqlyog (Windows and Linux)


Other

  • Node.js
  • NPM (Installed with node.js): npm is a package manager for the JavaScript to work with front end stuff like node.js, react.js, bootstrap, tailwind CSS,
  • Yarn (NPM alternative from Facebook)
  • GIT: track changes in source code