-
composer.json
Open in GitHub{ // "require": { // "laravel/socialite": "^5.0" } // }
-
routes/web.php
Open in GitHubuse Illuminate\Support\Facades\Route; use App\Http\Controllers\AppleSocialiteController; // Route::get('login/apple', [AppleSocialiteController::class, 'redirect'])->name('apple-login'); Route::post('login/apple', [AppleSocialiteController::class, 'callback']); //
-
app/Http/Controllers/AppleSocialiteController.php
Open in GitHubuse App\Models\User; use Illuminate\Support\Str; use Laravel\Socialite\Contracts\User as SocialiteUser; use Laravel\Socialite\Facades\Socialite; class AppleSocialiteController { public function redirect() { session()->reflash(); if (auth()->check()) { session()->put('auth-user-id', auth()->user()->id); } return Socialite::driver('apple')->redirect(); } public function callback() { session()->replace(json_decode(request('state'), true)); $appleUser = Socialite::driver('apple')->user(); $user = $this->retrieveUser($appleUser); $user->update([ 'apple_id' => $appleUser->getId(), ]); auth()->login($user, true); flash()->success('You have been logged in'); return view('auth.appleCallback'); } protected function retrieveUser(SocialiteUser $appleUser): User { if (session('auth-user-id')) { return User::find(session('auth-user-id')); } if ($appleUser->getEmail() && $user = User::where('email', $appleUser->getEmail())->first()) { return $user; } return User::firstOrCreate([ 'apple_id' => $appleUser->getId(), ], [ 'password' => bcrypt(Str::random()), 'email' => $appleUser->getEmail(), 'name' => $appleUser->getName() ?? $appleUser->getNickname() ?? $appleUser->getEmail(), ]); } }
-
app/Providers/AuthServiceProvider.php
Open in GitHubuse App\Support\Socialite\SignInWithAppleProvider; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Laravel\Socialite\Facades\Socialite; class AuthServiceProvider extends ServiceProvider { public function boot() { // Socialite::extend('apple', function () { return Socialite::buildProvider( SignInWithAppleProvider::class, config('services.apple'), ); }); } }
-
resources/views/auth/login.blade.php
Open in GitHub// ... <div> <a href="{{ route('apple-login') }}"> <x-button> <span class="-ml-3 mr-3 icon w-4 mb-1 opacity"> {{ svg('apple') }} </span> Sign-in with Apple </x-button> </a> </div> // ...