Laravel 11 Socialite Login with Slack Account Example

By Hardik Savani September 4, 2024 Category : Laravel

In this article, I will show you laravel 11 login with slack account using socialite composer package. we can use with laravel ui, laravel jetstream and laravel breaze for login with slack account.

As we know, social media becomes more and more popular in the world. Everyone has a social account like slack, github, Gmail, Facebook, twitter etc. I think also most have slack accounts. So if your application has login with social, then it becomes awesome. You get more people to connect with your website because most of the people do not want to fill out the sign-up or sign-in form. If they login with social, then it becomes awesome.

In this example, we will install the Socialite composer package for login with slack Account. Then we will install Laravel UI for Bootstrap authentication. After that, we will add a login with slack button, allowing users to log in and register using their slack account. So, let's follow the steps below:

laravel 11 login with slack

Step for Login with Slack Account in Laravel 11?

  • Step 1: Install Laravel 11
  • Step 2: Install Laravel UI
  • Step 3: Install Socialite
  • Step 4: Create Slack App
  • Step 5: Add slack_id Column
  • Step 6: Create Routes
  • Step 7: Create Controller
  • Step 8: Update Blade File
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Laravel UI

Now, in this step, we need to use Composer command to install Laravel UI, so let's run the below command and install the below library.

composer require laravel/ui

Now, we need to create authentication using the below command. You can create basic login, register, and email verification. We will run the below commands to create Bootstrap auth scaffold:

php artisan ui bootstrap --auth

Now, let's node js package:

npm install

let's run package:

npm run build

Step 3: Install Socialite

In the first step, we will install the Socialite Package, which provides an API to connect with slack accounts. So, first open your terminal and run the below command:

composer require laravel/socialite

Step 4: Create Slack App

To create our slack app and receive the app credentials open the Slack App and sign up or log in.

To guide you through the steps listed above, I’ve included screenshots of the entire process below:

1. Create New Application

2. Choose "From Scratch" option and click next.

3. Add Name and Click on submit button

4. Go to OAuth & Permission Section and add callback URL with scopes:

5. Copy Client ID and Secret from this screen and add on .env file.

Now you have to set app id, secret and call back URL in config file so open config/services.php and set id and secret this way:

config/services.php

return [
    ....

    'slack' => [
        'client_id' => env('SLACK_CLIENT_ID'),
        'client_secret' => env('SLACK_CLIENT_SECRET'),
        'redirect' => env('SLACK_REDIRECT_CALLBACK_URL'),
    ],
]

Then you need to add slack client id and client secret in .env file:

.env

SLACK_CLIENT_ID=7376807133985.7357628459782
SLACK_CLIENT_SECRET=43529a4d0dddb1d591f85f701...
SLACK_REDIRECT_CALLBACK_URL=https://localhost:8000/auth/slack/callback

Step 5: Add slack_id Column

In this step, first, we have to create a migration to add the slack_id in your user table. So let's run the below command:

php artisan make:migration add_slack_id_column

Migration

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('users', function ($table) {
            $table->string('slack_id')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        //
    }
};

Now, run the migration command:

php artisan migrate

Update mode like this way:

app/Models/User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

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

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

    /**
     * Get the attributes that should be cast.
     *
     * @return array
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }
}

Step 6: Create Routes

After adding the `slack_id` column, first, we have to add new routes for slack login. So let's add the below route in the `routes.php` file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\SlackController;
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
  
Route::controller(SlackController::class)->group(function(){
    Route::get('auth/slack', 'redirectToSlack')->name('auth.slack');
    Route::get('auth/slack/callback', 'handleSlackCallback');
});

Step 7: Create Controller

After adding the routes, we need to add a method for slack authentication. This method will handle the slack callback URL, etc. First, put the code below in your SlackController.php file.

app/Http/Controllers/SlackController.php

<?php
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
    
class SlackController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToSlack()
    {
        return Socialite::driver('slack')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleSlackCallback()
    {
        try {
        
            $user = Socialite::driver('slack')->user();
         
            $findUser = User::where('slack_id', $user->id)->first();
         
            if($findUser){
         
                Auth::login($findUser);
        
                return redirect()->intended('home');
         
            }else{
                $newUser = User::updateOrCreate(['email' => $user->email],[
                        'name' => $user->name,
                        'slack_id'=> $user->id,
                        'password' => encrypt('123456dummy')
                    ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('home');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Step 8: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Login') }}</div>

                <div class="card-body">
                    <form method="POST" action="{{ route('login') }}">
                        @csrf

                        <div class="row mb-3">
                            <label for="email" class="col-md-4 col-form-label text-md-end">{{ __('Email Address') }}</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>

                                @error('email')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <label for="password" class="col-md-4 col-form-label text-md-end">{{ __('Password') }}</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">

                                @error('password')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6 offset-md-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>

                                    <label class="form-check-label" for="remember">
                                        {{ __('Remember Me') }}
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button type="submit" class="btn btn-primary">
                                    {{ __('Login') }}
                                </button>

                                @if (Route::has('password.request'))
                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                @endif
                            </div>
                        </div>

                        <div class="row mb-0">
                            <div class="col-md-6 offset-md-4 mt-2">
                               <a class="btn btn-dark" href="{{ route('auth.slack') }}" 
                                   style="display: flex; align-items: center; justify-content: center; padding: 10px; 
                                   background-color: #4A154B; color: #FFFFFF; text-decoration: none; border-radius: 4px;">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 2447.6 2452.5" fill="none">
                                        <g clip-path="url(#clip0)">
                                            <path d="M476.2 1226.3C476.2 1030.8 625.9 881.1 821.4 881.1H1096.3V1156C1096.3 1351.4 946.6 1501.1 751.1 1501.1C555.7 1501.1 405.9 1351.4 405.9 1156H251.5C251.5 1408.6 492.4 1649.5 745 1649.5C997.6 1649.5 1238.5 1408.6 1238.5 1156V821.4C1238.5 625.9 1388.2 476.2 1583.6 476.2H1858.5V751.1C1858.5 946.6 1708.8 1096.3 1513.3 1096.3C1317.9 1096.3 1168.1 946.6 1168.1 751.1H1013.7C1013.7 1030.8 1262.6 1279.7 1542.3 1279.7C1822.1 1279.7 2071 1030.8 2071 751.1V405.9C2071 207.1 1884.8 20.9 1686 20.9H1411.1C1215.6 20.9 1065.9 170.6 1065.9 366.1V641C1065.9 836.5 915.2 986.2 719.7 986.2C524.3 986.2 374.5 836.5 374.5 641H220.1C220.1 1030.8 478.6 1226.3 751.1 1226.3H476.2Z" fill="#36C5F0"/>
                                            <path d="M1226.3 476.2C1226.3 671.6 1076.6 821.4 881.1 821.4H476.2V476.2C476.2 280.7 625.9 130.9 821.4 130.9H1226.3V476.2Z" fill="#2EB67D"/>
                                            <path d="M1076.6 1226.3C1076.6 1421.8 1226.3 1571.5 1421.8 1571.5H1858.5V1226.3H1421.8C1226.3 1226.3 1076.6 1376 1076.6 1571.5Z" fill="#ECB22E"/>
                                            <path d="M1226.3 1858.5C1226.3 2065.3 1376 2214.9 1582.8 2214.9H1858.5V1858.5H1582.8C1387.3 1858.5 1226.3 2009.5 1226.3 2214.9Z" fill="#E01E5A"/>
                                        </g>
                                        <defs>
                                            <clipPath id="clip0">
                                                <rect width="2447.6" height="2452.5" fill="white"/>
                                            </clipPath>
                                        </defs>
                                    </svg>
                                    <span style="margin-left: 10px;">Login with Slack</span>
                                </a>

                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/login

Output:

I hope it can help you...

Shares