
- Home
-
HTML
HTML Introduction HTML Tags HTML Elements HTML Attributes HTML Heading HTML Paragraph HTML Formatting HTML Quotations HTML Comments HTML Styles HTML Color HTML CSS HTML Images HTML Favicon HTML Links HTML DIV HTML Tables HTML Table Size HTML Table Head Table Padding & Spacing Table colspan rowspsn HTML Table Styling HTML Colgroup HTML List HTML Block & Inline HTML Classes HTML Id HTML Iframes HTML Head HTML Layout HTML Semantic Elements HTML Style Guide HTML Forms HTML Form Attribute HTML Form Element HTML input type HTML Computer code HTML Entity HTML Symbol HTML Emojis HTML Charset HTML Input Form Attribute HTML URL Encoding
-
CSS
CSS Introduction CSS Syntax CSS Selector How To Add CSS CSS Comments CSS Colors CSS Background color CSS background-image CSS Borders CSS Margins CSS Height, Width and Max-width CSS Box Model CSS Outline CSS Text CSS Fonts CSS Icon CSS Links CSS Tables CSS Display CSS Maximum Width CSS Position z-index Property
- JavaScript
-
JQuery
What is jQuery? Benefits of using jQuery Include jQuery Selectors. Methods. The $ symbol and shorthand. Selecting elements Getting and setting content Adding and removing elements Modifying CSS and classes Binding and Unbinding events Common events: click, hover, focus, blur, etc Event delegation Using .on() for dynamic content Showing and hiding elements Fading elements in and out Sliding elements up and down .animate() Understanding AJAX .ajax() .load(), .get(), .post() Handling responses and errors. Parent Chlid Siblings Filtering Elements Using find Selecting form elements Getting form values Setting form values Form validation Handling form submissions jQuery plugins Sliders plugins $.each() $.trim() $.extend() Data attributes Debugging jQuery code
-
Bootstrap 4
What is Bootstrap Benefits of using Setting up Container Row and Column Grid Classes Breakpoints Offsetting Columns Column Ordering Basic Typography Text Alignment Text colors Backgrounds Display Font Size Utilities Buttons Navs and Navbar Forms Cards Alerts Badges Progress Bars Margin Padding Sizing Flexbox Dropdowns Modals Tooltips Popovers Collapse Carousel Images Tables Jumbotron Media Object
- Git
-
PHP
PHP Introduction PHP Installation PHP Syntax PHP Comments PHP Variable PHP Echo PHP Data Types PHP Strings PHP Constant PHP Maths PHP Number PHP Operators PHP if else & if else if PHP Switch PHP Loops PHP Functions PHP Array PHP OOps PHP Class & Object PHP Constructor PHP Destructor PHP Access Modfiers PHP Inheritance PHP Final Keyword PHP Class Constant PHP Abstract Class PHP Superglobals PHP Regular Expression PHP Interfaces PHP Static Method PHP Static Properties PHP Namespace PHP Iterable PHP Form Introduction PHP Form Validation PHP Complete Form PHP Date and Time PHP Include Files PHP - Files & I/O File Upload PHP Cookies PHP SESSION PHP Filters PHP Callback Functions PHP JSON PHP AND Exceptions PHP Connect database
-
MY SQL
SQL Introduction Syntax Select statement Select Distinct WHERE Clause Order By SQL AND Operator SQL OR Operator SQL NOT Operator SQL LIKE SQL IN SQL BETWEEN SQL INSERT INTO SQL NULL Values SQL UPDATE SQL DELETE SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause SQL MIN() and MAX() Functions SQL COUNT() Function SQL SUM() SQL AVG() SQL Aliases SQL JOIN SQL INNER JOIN SQL LEFT JOIN SQL RIGHT JOIN SQL FULL OUTER JOIN SQL Self Join SQL UNION SQL GROUP BY SQL HAVING SQL EXISTS SQL ANY and ALL SQL SELECT INTO SQL INSERT INTO SELECT SQL CASE SQL NULL Functions SQL Stored Procedures SQL Comments SQL Operators SQL CREATE DATABASE SQL DROP DATABASE SQL BACKUP DATABASE SQL CREATE TABLE SQL DROP TABLE SQL ALTER TABLE SQL Constraints SQL NOT NULL SQL UNIQUE Constraint SQL PRIMARY KEY SQL FOREIGN KEY SQL CHECK Constraint SQL CREATE INDEX SQL AUTO INCREMENT SQL Dates SQL Views SQL Injection SQL Hosting SQL Data Types
Authentication in Laravel 8 π
Laravel provides a built-in authentication system that includes login, registration, password reset, and more. You can implement authentication using Laravelβs Jetstream, Breeze, or UI package.
1. Install Laravel Authentication System
Laravel offers different authentication options:
β Option 1: Laravel Breeze (Lightweight)
Breeze provides a simple authentication setup using Blade and Tailwind CSS.
composer require laravel/breeze --dev
php artisan breeze:install
php artisan migrate
npm install && npm run dev
php artisan serve
π This sets up login, registration, password reset, and email verification.
β Option 2: Laravel UI (Bootstrap-based)
Laravel UI provides authentication scaffolding for Blade and Bootstrap.
composer require laravel/ui
php artisan ui bootstrap --auth
npm install && npm run dev
php artisan migrate
php artisan serve
π This sets up authentication views with Bootstrap styling.
β Option 3: Laravel Jetstream (Advanced)
Jetstream provides authentication with Livewire or Inertia.js.
composer require laravel/jetstream
php artisan jetstream:install livewire
php artisan migrate
npm install && npm run dev
php artisan serve
π This includes authentication, two-factor authentication, session management, and API tokens.
2. Laravel Default Authentication Routes
After installing authentication, Laravel provides built-in routes for:
- Login (
/login
) - Register (
/register
) - Logout (
/logout
) - Forgot Password (
/forgot-password
) - Password Reset (
/reset-password
)
You can check available routes using:
php artisan route:list
3. Custom Authentication Logic
Laravelβs authentication system is powered by guards and providers.
β
Configuring authentication:
Modify config/auth.php
if needed.
β Changing the default guard:
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
β Middleware for authentication protection: To restrict access, use middleware in routes:
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware('auth');
4. Custom Login & Registration
If you need custom authentication, you can manually create controllers.
β
Custom Login Controller (app/Http/Controllers/Auth/LoginController.php
)
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::attempt($credentials)) {
return redirect()->intended('/dashboard');
}
return back()->withErrors(['email' => 'Invalid login details']);
}
public function logout()
{
Auth::logout();
return redirect('/');
}
}
β
Routes (routes/web.php
)
use App\Http\Controllers\Auth\LoginController;
Route::get('/login', [LoginController::class, 'showLoginForm'])->name('login');
Route::post('/login', [LoginController::class, 'login']);
Route::post('/logout', [LoginController::class, 'logout'])->name('logout');
5. Protecting Routes with Middleware
To protect pages, use auth
middleware.
β Example: Restrict access to dashboard
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware('auth');
β
Redirect users after login
Modify app/Providers/RouteServiceProvider.php
:
public const HOME = '/dashboard';
6. Role-Based Authentication
If you have different roles like Admin, User, Editor, define them in the users
table.
β
Add role column in users
migration
Schema::table('users', function (Blueprint $table) {
$table->string('role')->default('user');
});
β
Check role in middleware (app/Http/Middleware/CheckRole.php
)
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CheckRole
{
public function handle(Request $request, Closure $next, $role)
{
if (Auth::check() && Auth::user()->role === $role) {
return $next($request);
}
return redirect('/home')->with('error', 'Unauthorized access!');
}
}
β
Register middleware in app/Http/Kernel.php
protected $routeMiddleware = [
'role' => \App\Http\Middleware\CheckRole::class,
];
β Apply middleware in routes
Route::get('/admin', function () {
return "Welcome Admin";
})->middleware('role:admin');
7. Social Media Authentication (Google, Facebook, etc.)
Use Laravel Socialite for OAuth login.
β Install Socialite
composer require laravel/socialite
β
Configure OAuth in config/services.php
'google' => [
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect' => env('GOOGLE_REDIRECT_URL'),
],
β Routes for Social Login
use Laravel\Socialite\Facades\Socialite;
Route::get('/auth/google', function () {
return Socialite::driver('google')->redirect();
});
Route::get('/auth/google/callback', function () {
$user = Socialite::driver('google')->user();
// Handle user login/register logic
});
8. API Authentication (Laravel Sanctum)
For API authentication, use Laravel Sanctum.
β Install Sanctum
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
β
Enable Sanctum in app/Http/Kernel.php
protected $middlewareGroups = [
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
β Protect API Routes
use Illuminate\Http\Request;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
β Issue API Token
$user = Auth::user();
$token = $user->createToken('API Token')->plainTextToken;
β
Authenticate with Token
Use Authorization: Bearer <token>
in API requests.
Conclusion
Laravel makes authentication quick and secure with built-in tools. You can use:
- Laravel Breeze (simple Blade-based authentication)
- Laravel UI (Bootstrap-based)
- Laravel Jetstream (Livewire & Inertia.js)
- Laravel Sanctum (API authentication)
Let me know if you need help implementing any of these! π
Authorization in Laravel (Roles & Permissions) π
Laravel provides Authorization using Gates and Policies, allowing control over user access.
1. Authentication vs Authorization
- Authentication: Verifies who the user is (login).
- Authorization: Determines what a user can do (permissions, roles).
2. Gates (Simple Authorization)
Gates are closures that define authorization logic.
β
Define a Gate in AuthServiceProvider.php
π app/Providers/AuthServiceProvider.php
use Illuminate\Support\Facades\Gate;
use App\Models\User;
public function boot()
{
Gate::define('edit-posts', function (User $user) {
return $user->is_admin; // Only admins can edit posts
});
}
β Use in Controllers or Views
if (Gate::allows('edit-posts')) {
echo "You can edit posts.";
} else {
echo "Access denied.";
}
β Use in Blade Template
@can('edit-posts')
<button>Edit Post</button>
@endcan
3. Policies (Advanced Authorization)
Policies handle authorization for models.
β
Create a Policy for Post
Model
php artisan make:policy PostPolicy --model=Post
π File: app/Policies/PostPolicy.php
use App\Models\User;
use App\Models\Post;
public function update(User $user, Post $post)
{
return $user->id === $post->user_id; // Only post owners can edit
}
β
Register Policy in AuthServiceProvider.php
protected $policies = [
Post::class => PostPolicy::class,
];
β Using Policies in Controllers
$this->authorize('update', $post);
β Blade Authorization Check
@can('update', $post)
<button>Edit</button>
@endcan
4. Role-Based Access Control (RBAC)
Laravel does not have built-in roles, but you can define them manually.
β
Add role
Column to users
Table
php artisan make:migration add_role_to_users_table
π File: Migration
Schema::table('users', function (Blueprint $table) {
$table->string('role')->default('user');
});
β
Define Middleware for Roles
π File: app/Http/Middleware/CheckRole.php
use Closure;
public function handle($request, Closure $next, $role)
{
if (auth()->user()->role !== $role) {
abort(403, 'Unauthorized');
}
return $next($request);
}
β
Register Middleware in Kernel.php
protected $routeMiddleware = [
'role' => \App\Http\Middleware\CheckRole::class,
];
β
Use Middleware in Routes
π File: routes/web.php
Route::get('/admin', function () {
return "Admin Panel";
})->middleware('role:admin');
5. Laravel Permissions Package (Spatie)
To handle roles & permissions dynamically, use Spatie Laravel Permission.
β Install Package
composer require spatie/laravel-permission
β Publish Config & Migrate
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
β
Add HasRoles
Trait to User
Model
π File: app/Models/User.php
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasRoles;
}
β Create Roles & Permissions
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
$role = Role::create(['name' => 'admin']);
$permission = Permission::create(['name' => 'edit posts']);
$role->givePermissionTo($permission);
$user = User::find(1);
$user->assignRole('admin');
β Check Role & Permissions
if ($user->hasRole('admin')) {
echo "User is an admin.";
}
if ($user->can('edit posts')) {
echo "User can edit posts.";
}
β Use in Blade
@role('admin')
<button>Admin Panel</button>
@endrole
@can('edit posts')
<button>Edit Post</button>
@endcan
Conclusion
Laravel provides flexible authorization through Gates, Policies, Middleware, and Role-Based Access Control (RBAC). For large apps, Spatie Laravel Permission is recommended.
π Need more help? π
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.