1. Go to this page and download the library: Download nickmoline/stytch-laravel library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
namespace App\Models;
use Illuminate\Contracts\Auth\Authenticatable;
use LaravelStytch\Contracts\StytchUserContract;
use LaravelStytch\Traits\HasStytchUser;
use LaravelStytch\Traits\StytchAuthenticatable;
class User implements Authenticatable, StytchUserContract
{
use HasStytchUser, StytchAuthenticatable;
protected $fillable = [
'name',
'email',
'stytch_user_id',
];
/**
* Update the user's name from Stytch data.
* Override this method if your name field has a different name.
*/
public function updateStytchName(string $name): void
{
$this->name = $name;
}
/**
* Get the user's current name.
* Override this method if your name field has a different name.
*/
public function getStytchName(): ?string
{
return $this->name;
}
}
// Login with credentials
Auth::attempt(['email' => $email, 'password' => $password]);
// Login a user directly
Auth::login($user);
// Login using user ID
Auth::loginUsingId($userId);
// Login without session (stateless)
Auth::once(['email' => $email, 'password' => $password]);
// Logout the current user
Auth::logout();
// Check if user is authenticated
if (Auth::check()) {
// User is logged in
}
// Get current user
$user = Auth::user();
// Get user ID
$userId = Auth::id();
namespace App\Models;
use LaravelStytch\Traits\HasStytchOrganization;
class Organization extends Model
{
use HasStytchOrganization;
protected $fillable = [
'name',
'stytch_organization_id',
];
}
// Apply to individual routes
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware('stytch.auth');
// Apply to route groups
Route::middleware(['stytch.auth'])->group(function () {
Route::get('/profile', 'ProfileController@show');
Route::get('/settings', 'SettingsController@show');
});
// Apply to controllers
Route::controller(ProfileController::class)
->middleware('stytch.auth')
->group(function () {
Route::get('/profile', 'show');
Route::put('/profile', 'update');
});
// Get Stytch session data
$sessionData = Auth::guard('b2b')->getStytchSessionData();
// Clear Stytch session
Auth::guard('b2b')->clearStytchSession();
// Custom authentication with additional logic
$user = Auth::guard('b2c')->getProvider()->retrieveByCredentials([
'email' => $email,
'password' => $password,
]);
if ($user && Auth::guard('b2c')->getProvider()->validateCredentials($user, $credentials)) {
Auth::login($user);
// Custom logic here
}