Web Framework and Services — Study Notes

Unit 04

Composer, Artisan, Blade Templates, Migrations, Eloquent ORM, RESTful APIs & Middleware in Laravel

7 Questions 5 Marks Each Web Framework and Services
01
5 Marks Question

Explain Laravel Composer in Detail

Composer is a dependency management tool for PHP. In Laravel, it is used to install Laravel, install required PHP packages/libraries, manage project dependencies, and update packages when required.

Uses of Composer in Laravel

Installing Laravel
Composer helps install the Laravel framework.
Installing PHP packages
It installs libraries and packages required by the project.
Managing dependencies
It keeps track of the packages required by a Laravel project.
Updating packages
It can update existing project dependencies.
Adding or removing packages
Developers can easily add or remove packages as required.

Important Composer Commands

CommandPurpose
composer -VChecks the Composer version
composer installInstalls project dependencies
composer updateUpdates project dependencies
composer require package-nameAdds a package to the project
composer remove package-nameRemoves a package

Example

Suppose we want to add a PHP package to a Laravel project:

composer require package-name

Composer downloads and makes the required package available to the project. To install the dependencies already defined for a project:

composer install

To update the project's packages:

composer update

The notes also demonstrate running composer update --no-blocking from the Laravel project directory to update the PHP packages required by the project.

Composer and Laravel Project

Composer works with the Laravel project's dependency information. The Laravel folder structure includes:

composer.json
composer.lock
vendor/

composer.json — lists the PHP packages required by the project. composer.lock — stores the exact installed package versions. vendor — contains Laravel and other Composer packages.

Basic Working

Laravel Project
      ↓
composer.json
      ↓
Composer
      ↓
Install / Update Dependencies
      ↓
vendor/
      ↓
Laravel Application
Conclusion Composer is an essential tool for Laravel development. It manages PHP dependencies, installs required packages, updates them, and keeps the project's dependencies organized. Commands such as composer install, composer update, composer require, and composer remove make package management simple and efficient.
02
5 Marks Question

What is Artisan? Explain Artisan Commands

Artisan is Laravel's command-line interface (CLI) tool. It allows developers to perform various Laravel tasks by entering commands in the Command Prompt or Terminal, instead of performing them manually.

For example, instead of manually creating a controller file and writing its basic structure, Artisan can create it automatically:

php artisan make:controller StudentController

This creates:

app
└── Http
    └── Controllers
        └── StudentController.php

Important Artisan Commands

No.Artisan CommandPurpose
1php artisan listDisplays all available Artisan commands
2php artisan --versionDisplays the installed Laravel version
3php artisan serveStarts the Laravel development server
4php artisan route:listDisplays all registered routes
5php artisan make:controller StudentControllerCreates a controller
6php artisan make:model StudentCreates a model

Examples

1. Start Laravel development server:

php artisan serve

This starts the local Laravel development server.

2. Create a Controller:

php artisan make:controller StudentController

It automatically creates the controller in the appropriate directory.

3. Create a Model:

php artisan make:model Student

This creates the Student model for the Laravel application.

4. Display all available commands:

php artisan list

It displays the Artisan commands available in the Laravel project.

Advantages of Artisan

Reduces manual coding
Common files and structures are generated automatically.
Correct file placement
Automatically creates Laravel components in the correct locations.
Faster development
Makes common development tasks faster.
Useful commands
Provides many useful commands through the terminal.
Efficient management
Helps developers manage and work with Laravel applications efficiently.
Conclusion Artisan is Laravel's command-line toolbox that simplifies development and application management. Commands such as make:controller, make:model, serve, route:list, and --version help developers create components, run the application, inspect routes, and manage Laravel projects efficiently.
03
5 Marks Question

Explain Blade Template and Directives in Laravel

Blade Template

Blade is Laravel's built-in template engine used to create dynamic web pages. Blade templates are stored in the resources/views directory and normally use the .blade.php extension.

It allows developers to combine HTML with Laravel/PHP code using simple syntax and directives.

<!-- resources/views/student.blade.php -->

<h1>Student Details</h1>

<p>Name: {{ $name }}</p>
<p>Course: {{ $course }}</p>

Here, {{ }} is used to display data passed to the view.

Blade Directives

Blade directives are special commands provided by Laravel's Blade template engine. They generally begin with the @ symbol and are used for common programming tasks such as conditions, loops, and including other views.

01
@if Directive

Used to perform conditional operations.

@if($marks >= 40)
    <p>Pass</p>
@else
    <p>Fail</p>
@endif

It displays content based on whether the condition is true or false.

02
@foreach Directive

Used to loop through an array or collection.

@foreach($students as $student)
    <p>{{ $student }}</p>
@endforeach

It displays each student from the $students collection.

03
@include Directive

Used to include another Blade view inside the current view.

@include('header')

This is useful for reusable sections such as headers, footers, or menus.

Common Blade Directives

DirectivePurpose
@ifPerforms conditional checking
@elseExecutes when the @if condition is false
@foreachRepeats content for each item
@includeIncludes another Blade view
@endifEnds an @if block
@endforeachEnds a @foreach loop

Advantages of Blade

Simple syntax
Makes PHP code easier to write inside HTML.
Dynamic pages
Allows data to be displayed dynamically.
Reusable views
@include allows common sections to be reused.
Easy conditions and loops
Directives make programming logic cleaner.
Better organization
Views are separated from application logic.
Conclusion Blade is Laravel's template engine for creating dynamic web pages. Blade templates use the .blade.php extension and support special @ directives such as @if, @foreach, and @include. These features make Laravel views simple, dynamic, and reusable.
04
5 Marks Question

Explain Migrations in Laravel

Migration in Laravel is a feature used to create and manage the structure of a database using PHP code. It allows developers to define database tables, columns, data types, primary keys, foreign keys, and indexes in a structured way.

Migrations are useful because the same database structure can be maintained across different development environments and the database structure can be managed through version control.

Creating a Migration

A migration can be created using the Artisan command:

php artisan make:migration create_students_table

This creates a migration file for the students table. A model and migration can also be created together:

php artisan make:model Student -m

Migration Structure

A migration generally contains two important methods: up(), which defines the changes to be made to the database, and down(), which defines how to reverse those changes. For example:

public function up()
{
    Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('students');
}

Here, the up() method creates the students table, while down() removes it when the migration is rolled back.

Running Migrations

After creating a migration, it can be executed using:

php artisan migrate

This command runs all pending migrations. Laravel maintains a migration table to keep track of migrations that have already been executed.

Important Migration Commands

CommandPurpose
php artisan make:migration create_students_tableCreates a migration file
php artisan migrateRuns pending migrations
php artisan migrate:statusShows migration status
php artisan migrate:rollbackRolls back the latest migration batch
php artisan migrate:resetRolls back all migrations
php artisan migrate:refreshRolls back and runs migrations again
php artisan migrate:freshDrops all tables and runs all migrations again
php artisan migrate:fresh --seedDrops tables, runs migrations, and executes seeders

Migration Process

Create Migration
       ↓
Define Table Structure
       ↓
php artisan migrate
       ↓
Database Table Created
       ↓
Laravel Records Migration

Advantages of Migrations

Database version control
Database structure can be tracked.
Consistency
The same database structure can be maintained across environments.
Easy modification
Tables and columns can be changed through migration files.
Rollback support
Changes can be reversed using migrate:rollback.
Team development
Developers can share database structure through migration files.
Conclusion Laravel migrations provide a systematic way to create, modify, track, and reverse database structures. Using Artisan commands such as make:migration, migrate, and migrate:rollback, developers can efficiently manage the database throughout the development process.
05
5 Marks Question

Explain Eloquent ORM in Laravel

Eloquent ORM (Object-Relational Mapping) is Laravel's built-in ORM system. It allows developers to interact with database tables using PHP models and objects, instead of writing complex SQL queries directly.

Generally, an Eloquent Model represents a database table and provides methods for performing database operations such as CRUD. Eloquent models are generally stored in app/Models.

Example of an Eloquent Model

Suppose we have a students table. We can create a model:

php artisan make:model Student

The model can then be used to interact with the students table.

class Student extends Model
{
    protected $table = 'students';
}

Now, database operations can be performed using the Student model.

CRUD Operations Using Eloquent

01
Create

To insert a new record:

Student::create([
    'name' => 'Rahul',
    'email' => 'rahul@example.com'
]);

The create() method inserts a new record into the database.

02
Read

To retrieve all students:

$students = Student::all();

To retrieve a particular record:

$student = Student::find(1);

all() retrieves all records, while find() retrieves a record using its primary key.

03
Update

A record can be updated using:

$student = Student::find(1);

$student->name = 'Amit';
$student->save();
04
Delete

A record can be deleted using:

$student = Student::find(1);
$student->delete();

Important Eloquent Features

Query Building
Allows database queries to be constructed easily.
Model Relationships
Supports relationships between database tables.
Mass Assignment
Allows multiple model attributes to be assigned at once.
Attribute Handling
Provides mechanisms for working with model attributes.
Timestamps
Supports automatic handling of timestamps.

Advantages of Eloquent ORM

Reduces the need to write complex SQL queries; represents database tables using PHP models; provides simple methods for CRUD operations; supports relationships between tables; provides a powerful query-building system; makes database code easier to read and maintain; and integrates naturally with Laravel controllers and applications.

Conclusion Eloquent ORM provides a simple and object-oriented way to interact with databases in Laravel. By representing tables as PHP models, it makes operations such as Create, Read, Update, and Delete (CRUD) easier, while also supporting relationships and query building.
06
5 Marks Question

Explain the Use of RESTful APIs in Laravel

REST stands for Representational State Transfer. A RESTful API allows different applications or devices to communicate with a Laravel application using standard HTTP methods. Data is usually exchanged in JSON format.

RESTful APIs in Laravel are commonly used to perform CRUD operations on resources such as students, products, employees, etc.

Use of RESTful APIs

Suppose we have a Student Management System built with Laravel and MySQL. An Android application, React/Angular website, or another application may need to access the student data. Instead of allowing each application to directly connect to the database, Laravel provides a RESTful API:

Android App       ─┐
React/Angular App  ├──→ RESTful API → Laravel → MySQL
Other Application ─┘

This provides a common interface through which different applications can access the same data.

HTTP Methods Used in REST

HTTP MethodPurposeExample
GETRetrieve dataGet all students
POSTCreate new dataAdd a student
PUT/PATCHUpdate existing dataUpdate student details
DELETEDelete dataDelete a student

RESTful Routing in Laravel

Laravel provides routes for handling API requests. API routes are normally defined in routes/api.php. For example:

Route::get('/students', [StudentController::class, 'index']);

Route::post('/students', [StudentController::class, 'store']);

Route::get('/students/{id}', [StudentController::class, 'show']);

Route::put('/students/{id}', [StudentController::class, 'update']);

Route::delete('/students/{id}', [StudentController::class, 'destroy']);

These routes connect HTTP requests to appropriate controller methods.

Example

If an Android application sends:

GET /students

Laravel processes the request and can return student data in JSON format:

[
    {
        "id": 1,
        "name": "Rahul",
        "course": "BCA"
    },
    {
        "id": 2,
        "name": "Amit",
        "course": "BCA"
    }
]

The client application can then use this data to display the student information.

Advantages of RESTful APIs

Platform independent
Android, web, or other applications can communicate with Laravel.
Data sharing
Multiple applications can access the same resources.
Standard communication
Uses standard HTTP methods such as GET, POST, PUT, and DELETE.
CRUD support
Makes it convenient to create, retrieve, update, and delete resources.
JSON data exchange
Data can easily be exchanged between different applications.
Conclusion RESTful APIs in Laravel provide a standard way for different applications and devices to communicate with a Laravel application. Laravel uses HTTP methods such as GET, POST, PUT/PATCH, and DELETE to perform CRUD operations, with API routes generally defined in routes/api.php.
07
5 Marks Question

What is Middleware for API Security?

Middleware in Laravel is a mechanism that filters HTTP requests before they reach the application or controller. It can be used for authentication, authorization, request validation, logging, and other security-related tasks.

For APIs, middleware helps ensure that only authorized users can access protected routes.

Middleware for API Security

Middleware can perform several security checks before allowing an API request to continue:

Authentication
Checks whether the user is authenticated.
Authorization
Checks whether the user has permission to access a particular resource.
Route Protection
Restricts access to sensitive API routes.
Request Validation
Checks whether incoming requests are valid.
Request Logging
Records API requests when required.
Unauthorized Access Prevention
Prevents users without proper access from reaching protected resources.

Working of Middleware

Client / API Request
        ↓
    Middleware
        ↓
  Security Checks
   /           \
Failed        Passed
  ↓             ↓
Reject       Controller
Request          ↓
             Response

If the security checks fail, the request is rejected. If they pass, the request is forwarded to the appropriate controller.

Creating Middleware

Laravel provides an Artisan command to create middleware:

php artisan make:middleware CheckUser

This creates a middleware class that can contain the required checking logic. A simple example:

public function handle($request, Closure $next)
{
    if (!$request->user()) {
        return response()->json([
            'message' => 'Unauthorized'
        ], 401);
    }

    return $next($request);
}

Here, the middleware checks whether the request has an authenticated user. If not, it returns an Unauthorized response; otherwise, $next($request) allows the request to continue.

Example of Protected API Route

Route::middleware(['auth'])->group(function () {

    Route::get('/students', [StudentController::class, 'index']);

});

Here, the authentication middleware runs before the /students API is accessed.

Benefits of Middleware

Authentication
Provides authentication.
Authorization
Provides authorization.
Route protection
Protects sensitive API routes.
Access prevention
Prevents unauthorized users from accessing resources.
Separation of concerns
Keeps security logic separate from controller logic.
Conclusion Middleware acts as a security layer between the client request and the Laravel controller. It can authenticate users, authorize access, validate requests, and protect sensitive API routes, making it an important part of API security in Laravel.