College of Information Technology
First Semester, A.Y. 2024 - 2025
MODULE 1
INTRODUCTION TO LARAVEL
Introduction
This module entitled INTRODUCTION AND WEB PAGE BUILDING BLOCKS is about HTML
elements are the building blocks of the HTML web page. The elements consist of a pair of tags (starting
and ending tags) and the textual or graphical content inside of the tags.
Date and Time Allotment
Week 1
I. Objectives
At the end of the end of this module, students should be able to:
1. Identify the Key Features of Laravel
2. Understand the MVC Architecture
3. Identify System Requirements
4. Learn to Install Laravel
5. Identify the Key Directories in Laravel
II. Lecture
Key Features of Laravel
Elegant Syntax: Laravel provides a clean and expressive syntax, making it easy to read and write
code. This enhances developer productivity and enjoyment.
MVC Architecture: Laravel follows the Model-View-Controller (MVC) architectural pattern, which
separates application logic from the user interface, promoting organized and maintainable code.
Eloquent ORM: Laravel includes Eloquent, a powerful Object-Relational Mapping (ORM) system
that simplifies database interactions. It allows developers to work with database records as if they
were simple PHP objects.
Routing: Laravel provides a simple and intuitive routing mechanism, allowing developers to define
routes easily and handle HTTP requests with clean and readable code.
Blade Templating Engine: Blade is Laravel's built-in templating engine, enabling developers to
create dynamic and reusable views with a straightforward syntax and features like template
inheritance.
Artisan Console: Laravel includes a command-line interface called Artisan, which provides various
helpful commands for tasks like database migrations, seeding, and generating boilerplate code.
Middleware: Laravel's middleware feature allows developers to filter and manipulate HTTP requests
entering their application. This is useful for implementing authentication, logging, and other request-
based functionalities.
Security Features: Laravel comes with built-in security features, such as protection against SQL
injection, cross-site request forgery (CSRF), and cross-site scripting (XSS). It also supports user
authentication and authorization.
Task Scheduling: Laravel simplifies task scheduling with its built-in scheduling feature, allowing
developers to easily define scheduled tasks using a clean syntax.
Testing Support: Laravel provides robust testing capabilities, including built-in support for PHPUnit,
making it easier to write and run automated tests for your applications.
Package Ecosystem: Laravel has a rich ecosystem of packages and extensions, allowing
developers to easily integrate additional functionality into their applications.
Community and Documentation: Laravel has a large and active community, along with extensive
documentation that makes it easier for developers to learn and find solutions to problems.
These key features make Laravel a powerful framework for building web applications, providing
developers with the tools and flexibility they need to create robust, scalable, and maintainable
applications.
Understand the MVC Architecture
What is MVC?
MVC stands for Model-View-Controller, which is a design pattern used for developing web
applications. It separates an application into three interconnected components, allowing for organized
code and better separation of concerns:
1. Model: Represents the data and business logic of the application. It manages the data, logic,
and rules of the application. In Laravel, Eloquent ORM serves as the model component, allowing
you to interact with the database and define relationships between data entities.
2. View: Represents the user interface of the application. It displays data to the user and sends
user commands to the controller. In Laravel, views are typically created using the Blade
templating engine, which allows for the separation of presentation logic from business logic.
3. Controller: Acts as an intermediary between the Model and the View. It receives input from the
user, processes it (often by interacting with the Model), and returns the appropriate View. In
Laravel, controllers are responsible for handling incoming HTTP requests, performing actions
based on user input, and returning responses.
How MVC Works in Laravel
1. User Interaction: The user interacts with the application through a web browser, sending an
HTTP request (e.g., submitting a form or clicking a link).
2. Routing: The request is routed to the appropriate controller method based on the defined
routes in Laravel. Routes are defined in the routes/[Link] file.
3. Controller Logic: The controller method processes the request, possibly interacting with one or
more models to retrieve or manipulate data.
4. Model Interaction: The controller communicates with the Model to perform operations on the
data, such as querying the database or validating input.
5. Return View: After processing the data, the controller returns a View (often passing data to it)
that generates the final HTML output to be sent back to the user.
6. User Feedback: The View is rendered, and the resulting HTML is sent back to the user's
browser, where it is displayed. The user can then interact with the application again, starting
the process anew.
Benefits of MVC Architecture
Separation of Concerns: Each component (Model, View, Controller) has a distinct role,
making the application easier to manage and maintain.
Scalability: The MVC structure allows developers to work on different components
simultaneously without affecting others, making it easier to scale the application.
Testability: With clear separation, it is easier to write unit tests for the Model and Controller
without worrying about the View.
Reusability: Code written for the Model and Controller can often be reused in different parts of
the application or in different applications.
Identify System Requirements for Laravel 11
To run Laravel 11 applications, your server environment should meet the following minimum
requirements:
1. PHP Version
Minimum: PHP 8.1
Recommended: PHP 8.2 or higher for optimal performance and access to the latest features
and improvements.
2. Database
Laravel 11 supports various database systems, including:
MySQL: Version 5.7 or higher.
PostgreSQL: Version 9.4 or higher.
SQLite: Version 3.8.8 or higher.
SQL Server: Version 2017 or higher.
3. Composer
Composer: A dependency manager for PHP is required to install Laravel and manage its
dependencies. Make sure Composer is installed on your system.
4. Additional Recommendations
[Link] and NPM: For managing front-end assets (JavaScript/CSS), it's recommended to
have [Link] and npm (Node Package Manager) installed.
Learn to Install Laravel
To install Laravel, follow these steps:
Step 1: Install PHP and Composer
1. Check PHP Installation:
o Ensure you have PHP (version 8.1 or higher) installed. You can check your PHP
version by running the following command in your terminal or command prompt:
2. Install Composer:
o Composer is a dependency manager for PHP, and it's required to install Laravel.
Follow the instructions on the Composer website ([Link] to install
Composer globally on your system.
Step 2: Create a New Laravel Project
Before creating your first Laravel project, make sure that your local machine has PHP
and Composer installed. If you are developing on macOS or Windows, PHP, Composer, Node and NPM
can be installed in minutes via Laravel Herd.
After you have installed PHP and Composer, you may create a new Laravel project via
Composer's create-project command:
Once the project has been created, start Laravel's local development server using Laravel
Artisan's serve command:
Once you have started the Artisan development server, your application will be accessible in your web
browser at [Link] Next, you're ready to start taking your next steps into the Laravel
ecosystem. Of course, you may also want to configure a database.
Step 3: Database and Migration
Now that you have created your Laravel application, you probably want to store some data in a database.
By default, your application's .env configuration file specifies that Laravel will be interacting with a SQLite
database.
During the creation of the project, Laravel created a database/[Link] file for you, and ran the
necessary migrations to create the application's database tables.
If you prefer to use another database driver such as MySQL or PostgreSQL, you can update
your .env configuration file to use the appropriate database. For example, if you wish to use MySQL,
update your .env configuration file's DB_* variables like so:
If you choose to use a database other than SQLite, you will need to create the database and run your
application's database migrations:
Introduction Migrations
Migrations are like version control for your database, allowing your team to define and share the
application's database schema definition. If you have ever had to tell a teammate to manually add a
column to their local database schema after pulling in your changes from source control, you've faced
the problem that database migrations solve.
The Laravel Schema facade provides database agnostic support for creating and manipulating tables
across all of Laravel's supported database systems. Typically, migrations will use this facade to create
and modify database tables and columns.
Generating Migrations
You may use the make:migration Artisan command to generate a database migration. The new
migration will be placed in your database/migrations directory. Each migration filename contains a
timestamp that allows Laravel to determine the order of the migrations:
Laravel will use the name of the migration to attempt to guess the name of the table and whether or not
the migration will be creating a new table. If Laravel is able to determine the table name from the
migration name, Laravel will pre-fill the generated migration file with the specified table. Otherwise, you
may simply specify the table in the migration file manually.
Migration Structure
A migration class contains two methods: up and down. The up method is used to add new
tables, columns, or indexes to your database, while the down method should reverse the operations
performed by the up method.
Setting the Migration Connection
If your migration will be interacting with a database connection other than your application's
default database connection, you should set the $connection property of your migration:
Creating Tables
To create a new database table, use the create method on the Schema facade.
The create method accepts two arguments: the first is the name of the table, while the second is a closure
which receives a Blueprint object that may be used to define the new table:
When creating the table, you may use any of the schema builder's column
methods ([Link] to define the table's columns.
Key Directories in Laravel
The default Laravel application structure is intended to provide a great starting point for both
large and small applications. But you are free to organize your application however you like. Laravel
imposes almost no restrictions on where any given class is located - as long as Composer can autoload
the class.
The App Directory
The app directory contains the core code of your application. We'll explore this directory in more
detail soon; however, almost all of the classes in your application will be in this directory.
The Bootstrap Directory
The bootstrap directory contains the [Link] file which bootstraps the framework. This directory
also houses a cache directory which contains framework generated files for performance optimization
such as the route and services cache files.
The Config Directory
The config directory, as the name implies, contains all of your application's configuration files. It's
a great idea to read through all of these files and familiarize yourself with all of the options available to
you.
The Database Directory
The database directory contains your database migrations, model factories, and seeds. If you
wish, you may also use this directory to hold an SQLite database.
The Public Directory
The public directory contains the [Link] file, which is the entry point for all requests entering
your application and configures autoloading. This directory also houses your assets such as images,
JavaScript, and CSS.
The Resources Directory
The resources directory contains your views as well as your raw, un-compiled assets such as
CSS or JavaScript.
The Routes Directory
The routes directory contains all of the route definitions for your application. By default, two route
files are included with Laravel: [Link] and [Link].
The [Link] file contains routes that Laravel places in the web middleware group, which
provides session state, CSRF protection, and cookie encryption. If your application does not offer a
stateless, RESTful API then all your routes will most likely be defined in the [Link] file.
To learn more about directory just go to this link ([Link]
database-directory)
College of Information Technology
First Semester, A.Y. 2024 - 2025
MODULE 2
ROUTHING AND CONTROLLERS
Introduction
This module, entitled Routing and Controllers, forms the backbone of Laravel web applications.
Routing and controllers are essential components in Laravel, allowing you to define the application's
behavior for various URLs and manage the associated business logic for those routes.
Date and Time Allotment
Week 2
I. Objectives
At the end of the end of this module, students should be able to:
At the end of this module, students should be able to:
1. Know the fundamentals of Laravel routing and understand how to define routes for different
URLs.
2. Understand how to use route parameters and closures for creating dynamic and flexible
routing.
3. Learn to create and utilize controllers to organize and manage request handling logic.
4. Know how to link routes to controller methods effectively.
II. Lecture
Basic Routing
The most basic Laravel routes accept a URI and a closure, providing a very simple and expressive
method of defining routes and behavior without complicated routing configuration files:
The Default Route Files
All Laravel routes are defined in your route files, which are located in the routes directory. These files
are automatically loaded by Laravel using the configuration specified in your
application's bootstrap/[Link] file. The routes/[Link] file defines routes that are for your web
interface. These routes are assigned the web middleware group, which provides features like session
state and CSRF protection.
For most applications, you will begin by defining routes in your routes/[Link] file. The routes defined
in routes/[Link] may be accessed by entering the defined route's URL in your browser. For example,
you may access the following route by navigating to [Link] in your browser:
Named Routes
Named routes allow the convenient generation of URLs or redirects for specific routes. You may specify
a name for a route by chaining the name method onto the route definition:
Route Groups
Route groups allow you to share route attributes, such as middleware, across a large number of routes
without needing to define those attributes on each individual route.
Nested groups attempt to intelligently "merge" attributes with their parent group. Middleware and where
conditions are merged while names and prefixes are appended. Namespace delimiters and slashes in
URI prefixes are automatically added where appropriate.
Middleware
To assign middleware to all routes within a group, you may use the middleware method before defining
the group. Middleware are executed in the order they are listed in the array:
Controllers
If a group of routes all utilize the same controller, you may use the controller method to define the common
controller for all of the routes within the group. Then, when defining the routes, you only need to provide
the controller method that they invoke:
Middleware
Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your
application. 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 your application's
login screen. However, if the user is authenticated, the middleware will allow the request to proceed
further into the application.
Additional middleware can be written to perform a variety of tasks besides authentication. For example,
a logging middleware might log all incoming requests to your application. A variety of middleware are
included in Laravel, including middleware for authentication and CSRF protection; however, all user-
defined middleware are typically located in your application's app/Http/Middleware directory.
Defining Middleware
To create a new middleware, use the make:middleware Artisan command:
This command will place a new EnsureTokenIsValid class within your app/Http/Middleware directory. In
this middleware, we will only allow access to the route if the supplied token input matches a specified
value. Otherwise, we will redirect the users back to the /home URI:
As you can see, if the given token does not match our secret token, the middleware will return an HTTP
redirect to the client; otherwise, the request will be passed further into the application. To pass the request
deeper into the application (allowing the middleware to "pass"), you should call the $next callback with
the $request.
It's best to envision middleware 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.
CSRF Protection
Cross-site request forgeries are a type of malicious exploit whereby unauthorized commands are
performed on behalf of an authenticated user. Thankfully, Laravel makes it easy to protect your
application from cross-site request forgery (CSRF) attacks.
An Explanation of the Vulnerability
In case you're not familiar with cross-site request forgeries, let's discuss an example of how this
vulnerability can be exploited. Imagine your application has a /user/email route that accepts a POST
request to change the authenticated user's email address. Most likely, this route expects an email input
field to contain the email address the user would like to begin using.
Without CSRF protection, a malicious website could create an HTML form that points to your application's
/user/email route and submits the malicious user's own email address:
If the malicious website automatically submits the form when the page is loaded, the malicious user only
needs to lure an unsuspecting user of your application to visit their website and their email address will
be changed in your application.
To prevent this vulnerability, we need to inspect every incoming POST, PUT, PATCH, or DELETE request
for a secret session value that the malicious application is unable to access.
Preventing CSRF Requests
Laravel automatically generates a CSRF "token" for each active user session managed by the
application. This token is used to verify that the authenticated user is the person actually making the
requests to the application. Since this token is stored in the user's session and changes each time the
session is regenerated, a malicious application is unable to access it.
The current session's CSRF token can be accessed via the request's session or via the csrf_token helper
function:
Anytime you define a "POST", "PUT", "PATCH", or "DELETE" HTML form in your application, you should
include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the
request. For convenience, you may use the @csrf Blade directive to generate the hidden token input
field:
The Illuminate\Foundation\Http\Middleware\ValidateCsrfToken middleware, which is included in
the web middleware group by default, will automatically verify that the token in the request input matches
the token stored in the session. When these two tokens match, we know that the authenticated user is
the one initiating the request.
Controller
Instead of defining all of your request handling logic as closures in your route files, you may wish to
organize this behavior using "controller" classes. Controllers can group related request handling logic into
a single class. For example, a UserController class might handle all incoming requests related to users,
including showing, creating, updating, and deleting users. By default, controllers are stored in
the app/Http/Controllers directory.
Basic Controllers
To quickly generate a new controller, you may run the make:controller Artisan command. By default, all
of the controllers for your application are stored in the app/Http/Controllers directory:
Let's take a look at an example of a basic controller. A controller may have any number of public methods
which will respond to incoming HTTP requests:
Once you have written a controller class and method, you may define a route to the controller method
like so:
When an incoming request matches the specified route URI, the show method on
the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to
the method.
Controller Middleware
Middleware may be assigned to the controller's routes in your route files:
Or, you may find it convenient to specify middleware within your controller class. To do so, your controller
should implement the HasMiddleware interface, which dictates that the controller should have a
static middleware method. From this method, you may return an array of middleware that should be
applied to the controller's actions:
Interacting With The Request
Accessing the Request
To obtain an instance of the current HTTP request via dependency injection, you should type-hint
the Illuminate\Http\Request class on your route closure or controller method. The incoming request
instance will automatically be injected by the Laravel service container:
As mentioned, you may also type-hint the Illuminate\Http\Request class on a route closure. The service
container will automatically inject the incoming request into the closure when it is executed:
Dependency Injection and Route Parameters
If your controller method is also expecting input from a route parameter you should list your route
parameters after your other dependencies. For example, if your route is defined like so:
You may still type-hint the Illuminate\Http\Request and access your id route parameter by defining your
controller method as follows:
Creating Responses
Strings and Arrays
All routes and controllers should return a response to be sent back to the user's browser. Laravel provides
several different ways to return responses. The most basic response is returning a string from a route or
controller. The framework will automatically convert the string into a full HTTP response:
In addition to returning strings from your routes and controllers, you may also return arrays. The
framework will automatically convert the array into a JSON response:
Views
Of course, it's not practical to return entire HTML documents strings directly from your routes and
controllers. Thankfully, views provide a convenient way to place all of our HTML in separate files.
Views separate your controller / application logic from your presentation logic and are stored in
the resources/views directory. When using Laravel, view templates are usually written using the Blade
templating language. A simple view might look something like this:
Since this view is stored at resources/views/[Link], we may return it using the
global view helper like so: