0% found this document useful (0 votes)
28 views58 pages

8 - 1 - Laravel (Updated)

The document provides an overview of Composer, a dependency manager for PHP, and the Laravel framework, including its features like Artisan CLI, Eloquent ORM, and built-in security measures. It discusses routing, middleware, and controllers in Laravel, highlighting how to manage HTTP requests and implement security through middleware. The document also covers the use of migrations, unit testing, and Redis for data management within Laravel applications.

Uploaded by

mokishere
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views58 pages

8 - 1 - Laravel (Updated)

The document provides an overview of Composer, a dependency manager for PHP, and the Laravel framework, including its features like Artisan CLI, Eloquent ORM, and built-in security measures. It discusses routing, middleware, and controllers in Laravel, highlighting how to manage HTTP requests and implement security through middleware. The document also covers the use of migrations, unit testing, and Redis for data management within Laravel applications.

Uploaded by

mokishere
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Composer

• Dependency Manager for PHP


• Provides 3rd party libraries
• Current Version: 2.5.5
• Local Installation
• https://getcomposer.org/doc/00-intro.md
CSRF Protection
• Cross-site Request Forgery
• Read: https://laravel.com/docs/10.x/csrf
• Prevent malicious access to web urls
• Resolved via a secret session value (CSRF
token)
• Explicit exclusion is possible.
Laravel

The PHP framework for web artisans


What is Laravel?
• PHP Framework
• Web apps – Server End
• Enables Separation of Concerns through MVC
• Current Version: 10.x released in 2023
What is Laravel?
• Laravel also comes with:
• Artisan CLI: A command-line interface for tasks
like migrations, seeding, and scaffolding.
• Eloquent ORM: Simplifies database operations.
• Blade Template Engine: Helps in creating views
with reusable templates.
• Built-in Security Features: Protection against SQL
injection, XSS, and CSRF attacks.
Why Laravel?
• Separation of Concerns
• Scalable
• Simple
– Like PHP
– Clean Code
– Open Source (https://github.com/laravel)
• Well Documented
– Laracasts(Video Tutorials)
– Docs(http://laravel.com/docs/)
• Reusability
– Bundles => Packages
• Well Maintained
– Modern
– Follows Industry Standards
Artisan
• CLI for Laravel
• Provides commands to perform various
actions
• List all artisan commands: php artisan list
• Get help for a command: php artisan help migrate
• Also works with Tinker (REPL: read–eval–print
loop)
php artisan tinker
>>> echo "Hello, Tinker!";
Hello, Tinker!
Laravel Features
• Packages
• Eloquent ORM
• Migrations
• Unit-Testing
• Redis
• Queues
• Command Bus
Packages
• Laravel Repository to share code that is
– redistributable
– Useful
• Upto Laravel 4, these were called Bundles
• http://packalyst.com/packages
More about Packages
• Alternate to Composer
– Laravel Packages can access other Laravel Features

• Also useful, when organizing applications into


several “bundles” of smaller applications
Eloquent ORM
• Object-Relational Mapping
– Map your Relational Tables to Models(Classes)
• Really Cool!
– Simple
– Easy
– Supports CRUD inherently for all models
– Also supports model relationship management
Migrations
• Database schema manager
– like version control for your database
– easily modify and share the application's database
schema
A simple Migration

Schema::create('users', function (Blueprint $table) {


$table->id(); // Auto-incrementing primary key
$table->string('username')->unique(); // Username must be unique
$table->string('email')->unique(); // Email must be unique
$table->string('phone')->nullable(); // Phone is optional
$table->text('about')->nullable(); // Optional "About" section
$table->timestamps(); // created_at and updated_at columns
});
Unit-Testing
• Scenario: You want to test if your homepage loads
successfully and displays the correct content.
• Route:
Route::get('/', function () {
return view('welcome');
});
• Test:
public function test_homepage_loads_successfully()
{ // Simulates a GET request to the homepage
$response = $this->get('/');
$response->assertStatus(200); // Checks if the response
status is 200
$response->assertSee('Laravel'); // Checks if the content
"Laravel" is present in the page }
Redis
• NoSql: key-value database
• Can be used as a cache, database, or message broker.
• Requires predis/predis package installed via composer

Storing and Retrieving Data using Redis


Redis::set('name’, ‘Ayesha’); //Stores data

$user = Redis::get(‘name’); //Retrieves data


Routing
• Routing is used to define how your application
responds to different URL requests.
• Modern Laravel versions (starting from 5.x)
use routes/web.php
• 3 types:
– Basic Routing
– Route parameters
– Named Routes
Basic Routing
• Basic routing allows you to define a simple URL and specify the
logic (action) to execute when that URL is accessed.
// Define a basic route
Route::get('/hello', function () {
return 'Hello, World!';
});

// Route for POST request


Route::post('/submit', function () {
return 'Form submitted!';
});

• Route::get(): Handles GET requests to the /hello URL and


returns "Hello, World!".
• Route::post(): Handles POST requests to the /submit URL.
Automatic Dependency Injection
• Without Dependency Injection:
Route::get('/users', function () {
$request = new Illuminate\Http\Request(); // Manual
instantiation
// Handle the request here
});

• With Dependency Injection:


Route::get('/users', function (Request $request) {
// The $request object is automatically injected
});
Automatic Dependency Injection
• Automatically resolve classes and instantiate them
use Illuminate\Http\Request;

Route::get('/users', function (Request $request) {


// Handle the request here
});

What Does the Injected Request Object Provide?

1. Query Parameters ($_GET):


$name = $request->query('name'); // Retrieve the 'name' query parameter
2. Input Data ($_POST):
$email = $request->input('email'); // Retrieve the 'email' input field
3. Headers
$userAgent = $request->header('User-Agent'); // Get the browser's User-Agent
4. Files
$avatar = $request->file('avatar'); // Handle uploaded files
Connecting Requests to Actions
HTML form: • Laravel Route:
<form action="/submit-form" Route::post('/submit-form',
method="POST"> function (Request $request) {
@csrf $name = $request-
<input type="text" >input('name');
name="name" return "Submitted Name:
placeholder="Enter your name"> $name";
<button });
type="submit">Submit</button> •How It Works:
</form> • The form sends a POST request to
/submit-form.
• The route handles the request and
executes the defined logic (e.g.,
retrieving the form data).
Handling HTTP Methods
• Routing allows you to handle different HTTP methods (GET, POST, PUT,
DELETE) for the same endpoint.
• HTML forms primarily support GET and POST, but Laravel routes can
manage other HTTP methods for RESTful APIs or CRUD operations.

// Fetch a user
Route::get('/user/{id}', [UserController::class, 'show']);
// Create a user
Route::post('/user', [UserController::class, 'store']);
// Update a user
Route::put('/user/{id}', [UserController::class, 'update']);
// Delete a user
Route::delete('/user/{id}', [UserController::class, 'delete']);
Redirect Routes
Redirect routes are used in Laravel to send users from one URL to another. Laravel
provides a simple way to define redirection routes in your application.

Route::redirect('/old-route', '/new-route');

•/old-route: The URL users are trying to access.


•/new-route: The URL where users will be redirected.
•302 (default): The HTTP status code used for redirection.
View Routes
• Routes to view
Route::view('/welcome', ‘Hello');

Route::view('/welcome', ‘Hello', ['name' => ‘Ayesha']);


Route List
• Use artisan
php artisan route:list

• For middleware info


php artisan route:list -v

• Routes starting with a URI:


php artisan route:list --path=api
2. Route Parameters
Route parameters allow you to capture dynamic values from the
URL.

Route::get('user/{id}', function ($id) { Access: /user/5


Output: User ID: 5
return “User ID ”.$id;
});

Route::get('posts/{postId}/comments/{commentId}', function
($postId, $commentId) {
return “Post ID: $postId, Comment ID: $commentId”;
}); Access: /post/1/comments/2
Output: Post ID: 1, Comment ID: 2
Optional Parameters
• You can define optional parameters by adding
a ? at the end of the parameter name and
assigning a default value.

Route::get('user/{name?}', function ($name =


‘Guest’) {
return ‘Welcome ’.$name;
});
Access: /user/Ayesha Access: /user/
Output: Welcome Ayesha Output: Welcome Guest
Regular Expression based Constraints (1/2)

• where method

Route::get('/user/{name}', function (string $name) {


/ ...
})->where('name', '[A-Za-z]+'); • Valid Examples:/user/John
• Invalid Examples:/user/123
Route::get('/user/{id}', function (string $id) {
/ ... • Valid Examples:/user/123
})->where('id', '[0-9]+'); • Invalid Examples:/user/12abc

Route::get('/user/{id}/{name}', function (string $id, string $name) {


/ ...
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);• /user/42/alex
Regular Expression based Constraints (2/2)

• Convenience methods
Route::get('/user/{id}/{name}', function (string $id, string $name) {
// ...
})->whereNumber('id')->whereAlpha('name');

Route::get('/user/{name}', function (string $name) {


// ...
})->whereAlphaNumeric('name');

Route::get('/user/{id}', function (string $id) {


// ...
})->whereUuid('id');

Route::get('/user/{id}', function (string $id) {


//
})->whereUlid('id');

Route::get('/category/{category}', function (string $category) {


// ...
})->whereIn('category', ['movie', 'song', 'painting']);
Global Route Pattern Constraint
• Constraints on a parameter throughout the
web app
/**
* Define your route model bindings, pattern filters, etc.
*/
public function boot(): void
{
Route::pattern('id', '[0-9]+');
}

Route::get('/user/{id}', function (string $id) {


// Only executed if {id} is numeric...
});
Named Routes
• Name a route
Route::get('/user/profile', function () {
// ...
})->name('profile');

• Use for a controller action


Route::get(
'/user/profile',
[UserProfileController::class, 'show']
)->name('profile');
Name Routes Usage
• Name a route
// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

return to_route('profile');
Route Groups
• Share route attributes – With Controller

use App\Http\Controllers\OrderController;

Route::controller(OrderController::class)->group(function () {
Route::get('/orders/{id}', 'show');
Route::post('/orders', 'store');
});
MIDDLEWARE
What is a Middleware?
• A mechanism to process HTTP requests before
the business logic executes.
• Think of it as a series of "layers" HTTP requests
must pass through before they hit your
application.
– Each layer can examine the request and even
reject it entirely.
HTTP Middleware
• For example, Laravel includes a middleware
that verifies the user of your application is
authenticated.
– If the user is not authenticated, the middleware
will redirect the user to the login screen.
– However, if the user is authenticated, the
middleware will allow the request to proceed
further into the application.
Built-in Middleware
• In Laravel, middleware can be defined directly on a
route to apply additional functionality like
authentication, throttling, or other custom
middleware.
• auth is a built-in middleware provided by Laravel.

Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
})->middleware('auth');
Using Middleware in Route Groups
• Grouping Routes with Shared Middleware
– All routes in the group are protected by the auth middleware.

Route::middleware(['auth'])->group(function () {
Route::get('/profile', function () {
return 'User profile';
});

Route::get('/settings', function () {
return 'User settings';
});
});
Creating a Custom Middleware (1/2)
• Artisan command to create the custom
middleware

php artisan make:middleware CheckAge


Creating a Custom Middleware (2/2)
• When and how to execute?

namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;

class CheckAge
{
public function handle(Request $request, Closure $next)
{
// Middleware logic goes here
if ($request->age < 18) {
return redirect('home')->with('error', 'You are not old enough to
access this page.');
}
return $next($request);
}
}
Types of Middleware
• Global Middleware
• For tasks that should always run, no matter what
route is being accessed.
• Example: Enforcing SSL, adding security headers.
• Route based Middleware
– For tasks that should apply only to certain routes.
– Example: Protecting /dashboard with
authentication (auth middleware)
Global Middleware
• Create the middleware:
Effect:
php artisan make:middleware TrimInput
•All incoming requests will have their input
• Add logic in the middleware: values trimmed automatically.
•Example:
// app/Http/Middleware/TrimInput.php
• Input: name = " John Doe "
namespace App\Http\Middleware;
• Trimmed to: name = "John Doe"
use Closure;

class TrimInput
{
public function handle($request, Closure $next)
{
$request->merge(array_map('trim', $request->all())); // Trim all input values
return $next($request);
}
}
• Register it as global middleware in app/Http/Kernel.php:

protected $middleware = [
\App\Http\Middleware\TrimInput::class, // Add your middleware here
];
Rout-based Middleware
• Apply auth middleware to specific routes only to
authenticate users

Route::get('/dashboard', function () {
return 'Welcome to your dashboard!';
})->middleware('auth'); // Apply auth middleware

• Effect:
• The routes (/dashboard) will only be accessible to authenticated users.
• Unauthenticated users will be redirected to the login page.
CONTROLLERS
Controllers
• Object Oriented way to handle business logic
• Group together related requests in one class
• Add custom controllers in
app/Http/Controllers directory
php artisan make:controller TestController
Example: TestController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TestController extends Controller


{
public function test()
{
return view('test’);
}

}
Test View
Create /resources/views/test.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Test Page</title>
</head>
<body>
<h1>Welcome to the Test Page</h1>
<p>This is a simple test view.</p>
</body>
</html>
Set Route: TestController
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\TestController;

Route::get('/test', [TestController::class, 'test']);

• Now, when a request matches the specified route


URI, the test() method on the TestControllerclass will
be executed.
Controller Middleware
• Middleware may be assigned to the controller's routes like
so:

Route::get('/test', [TestController::class, 'test'])->middleware('auth');

• When you try to access test, you will receive the error
– Route [login] not defined.
• The error "Route [login] not defined" occurs because the
auth middleware is being applied to the route, but the login
route (where unauthenticated users are redirected) has not
been defined in your application.
What is happening?
• The auth middleware is used to protect the /test
route.
• When an unauthenticated user tries to access /test,
the middleware attempts to redirect them to the
login route.
• Since the login route is missing, Laravel throws the
error.
The simplest way to fix it…!
• Instead of manually defining the login route, you can
use Laravel's pre-built authentication scaffolding.
• Install Laravel Breeze (Simple Authentication):
composer require laravel/breeze --dev
php artisan breeze:install
npm install && npm run dev
php artisan migrate
• This will set up the login route and other basic
authentication routes.
Resource Controllers
• RESTful Resource Controllers
• API Resource Controllers
RESTful Resource Controllers
php artisan make:controller PhotoController --resource

app/Http/Controllers/PhotoController.php

use App\Http\Controllers\PhotoController;

Route::resource('photos', PhotoController::class);
Verb URI Action Route Name Purpose
GET /photos index photos.index Display all photos
GET /photos/create create photos.create Show a form to create a photo
POST /photos store photos.store Store a new photo
GET /photos/{photo} show photos.show Display a specific photo
GET /photos/{photo}/edit edit photos.edit Show a form to edit a photo
PUT/PATCH /photos/{photo} update photos.update Update a specific photo
DELETE /photos/{photo} destroy photos.destroy Delete a specific photo
Example: PhotoController.php
php artisan make:controller PhotoController --resource
A new controller file is created with predefined methods for CRUD operations.
class PhotoController extends Controller
{
public function index()
{
// Display a listing of the resource
}

public function create()


{
// Show the form for creating a new resource
}

public function store(Request $request)


{
// Store a newly created resource
}

public function show($id)


{
// Display a specific resource
}

public function edit($id)


{
// Show the form for editing a resource
}

public function update(Request $request, $id)


{
// Update a specific resource
}

public function destroy($id)


{
// Remove a specific resource
}
}
API Resource Controllers
php artisan make:controller PhotoController --api

app/Http/Controllers/PhotoController.php

use App\Http\Controllers\PhotoController;

Route::apiResource ('photos', PhotoController::class);


Verb URI Action Route Name
GET /photos index photos.index
GET /photos/create create photos.create
POST /photos store photos.store
GET /photos/{photo} show photos.show
GET /photos/{photo}/edit edit photos.edit
PUT/PATCH /photos/{photo} update photos.update
DELETE /photos/{photo} destroy photos.destroy
Singleton Resource Controllers
php artisan make:controller ProfileController --singleton

use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

Route::singleton('profile', ProfileController::class);

Verb URI Action Route Name


GET /profile show profile.show
GET /profile/edit edit profile.edit
PUT/PATCH /profile update profile.update
DELETE /profile destroy profile.destroy
A new Laravel Project
• Local installation
composer create-project --prefer-dist laravel/laravel project-
name
– OR Global Installation
composer global require laravel/installer

laravel new project-name

• cd
Deploy
project-name

php artisan serve

• Access
– http://localhost:8000 (or)
– http://127.0.0.1:8000
Other methods to get started
• https://laravel.com/docs/10.x#laravel-and-doc
ker
More Laravel, Next Time!

QUESTIONS?

You might also like