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
Important Composer Commands
| Command | Purpose |
|---|---|
| composer -V | Checks the Composer version |
| composer install | Installs project dependencies |
| composer update | Updates project dependencies |
| composer require package-name | Adds a package to the project |
| composer remove package-name | Removes 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
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 Command | Purpose |
|---|---|---|
| 1 | php artisan list | Displays all available Artisan commands |
| 2 | php artisan --version | Displays the installed Laravel version |
| 3 | php artisan serve | Starts the Laravel development server |
| 4 | php artisan route:list | Displays all registered routes |
| 5 | php artisan make:controller StudentController | Creates a controller |
| 6 | php artisan make:model Student | Creates 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
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.
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.
Used to loop through an array or collection.
@foreach($students as $student)
<p>{{ $student }}</p>
@endforeach
It displays each student from the $students collection.
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
| Directive | Purpose |
|---|---|
| @if | Performs conditional checking |
| @else | Executes when the @if condition is false |
| @foreach | Repeats content for each item |
| @include | Includes another Blade view |
| @endif | Ends an @if block |
| @endforeach | Ends a @foreach loop |
Advantages of Blade
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
| Command | Purpose |
|---|---|
| php artisan make:migration create_students_table | Creates a migration file |
| php artisan migrate | Runs pending migrations |
| php artisan migrate:status | Shows migration status |
| php artisan migrate:rollback | Rolls back the latest migration batch |
| php artisan migrate:reset | Rolls back all migrations |
| php artisan migrate:refresh | Rolls back and runs migrations again |
| php artisan migrate:fresh | Drops all tables and runs all migrations again |
| php artisan migrate:fresh --seed | Drops 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
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
To insert a new record:
Student::create([
'name' => 'Rahul',
'email' => 'rahul@example.com'
]);
The create() method inserts a new record into the database.
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.
A record can be updated using:
$student = Student::find(1);
$student->name = 'Amit';
$student->save();
A record can be deleted using:
$student = Student::find(1);
$student->delete();
Important Eloquent Features
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.
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 Method | Purpose | Example |
|---|---|---|
| GET | Retrieve data | Get all students |
| POST | Create new data | Add a student |
| PUT/PATCH | Update existing data | Update student details |
| DELETE | Delete data | Delete 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
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:
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.