It is a application level package manager for php that helps install and manage libraries, including Laravel itself.
Essential for handling dependencies!
Contracts are set of Interfaces in laravel application that define core services provided by the framework.
Example:
1) illuminate\Contracts\Queue.
2) illuminate\Contracts\Mailer.
A service provider in Laravel is a central place to configure an application. It's used to register services, event listeners, filters, and routes.
Service providers also inject the application's services into the service container.
A service provider in Laravel is a class that bootstraps an application by registering services and dependencies.
Path: config/app.php
It is a wrapper which provides static interface.
In a Laravel application, a facade is a class that provides access to an object from the container.
Example: View, Route, App, DB.
Service Container is a powerful tool to manage class dependency and dependency injection.
Why Use the Service Container?
Example:
Inject the User Model in the Constructor
You can use Dependency Injection to inject the User model into the controller. Laravel's Service Container automatically resolves it.
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
protected $user;
// Inject the User model into the constructor
public function __construct(User $user)
{
$this->user = $user;
}
// Get all users
public function index()
{
$users = $this->user->all();
return response()->json($users);
}
// Get a single user by ID
public function show($id)
{
$user = $this->user->find($id);
return response()->json($user);
}
// Create a new user
public function store(Request $request)
{
$user = $this->user->create($request->all());
return response()->json($user, 201);
}
}
?>
Explanation
Dependency Injection (DI) is a design pattern in which a class receives its dependencies from an external source rather than creating them itself. In Laravel, the Service Container manages these dependencies automatically.
Example:
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
protected $user;
// Dependency Injection in Constructor
public function __construct(User $user)
{
$this->user = $user;
}
public function index()
{
return response()->json($this->user->all());
}
}
?>
Laravel provides built-in features and best practices to protect against SQL injection attacks: Query Builder: Laravel's Query Builder provides a fluent interface for creating database queries using PHP code.
The Query Builder automatically escapes user input, preventing SQL injection attacks.
SQL injection attacks can be prevented by validating user input, using parameterized queries, and limiting access to databases.
Eloquent ORM (Object-Relational Mapping) is Laravel’s built-in ORM that provides an easy and expressive way to interact with databases using PHP models instead of writing raw SQL queries.
✅ Active Record Pattern – Each model represents a database table.
✅ Automatic Timestamps – created_at and updated_at are handled automatically.
✅ Relationships – Define relationships (One-to-One, One-to-Many, Many-to-Many, etc.).
✅ Query Builder Support – Write complex queries fluently.
✅ Mutators & Accessors – Modify attributes before saving or retrieving them.
Example:
$users = User::where('email', 'test@example.com')->get();
1. One to One / Has One
A one-to-one relationship means a record in one table is associated with a single record in another table.
Example:
A User has one Profile.
In Model
class User extends Model
{
//has one
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Query Example
$user = User::find(1);
$profile = $user->profile; // Fetch user’s profile
$profile = Profile::find(1);
$user = $profile->user; // Fetch profile's user
2. One to Many / Has Many
A one-to-many relationship means a record in one table can have multiple related records in another table.
Example:
A User has many Posts.
In Model
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Query Example:
$user = User::find(1);
$posts = $user->posts; // Fetch all posts of the user
$post = Post::find(1);
$user = $post->user; // Fetch the user who wrote the post
3. One to Many (Inverse) / Belongs To
The inverse of a one-to-many relationship means a record in a child table belongs to one record in a parent table.
Example:
A Post belongs to a User.
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Query Example:
$post = Post::find(1);
$user = $post->user; // Get the user who wrote the post
4. Has One of Many
This relationship is useful when a model has many related models, but you want only one specific related model.
Example:
A User has many Orders, but we want only the latest order.
class User extends Model
{
public function latestOrder()
{
return $this->hasOne(Order::class)->latest();
}
}
Query Example:
$user = User::find(1);
$latestOrder = $user->latestOrder; // Fetch only the latest order
5. Has One Through
A has-one-through relationship is used when you need to access a related model through an intermediate model
Example:
A User has one Account, but the relation is through Profile.
Database structure:
users, table: id
profiles, table: id, user_id
accounts, table: id, profile_id
class User extends Model
{
public function account()
{
return $this->hasOneThrough(Account::class, Profile::class);
}
}
// Profile.php (Model)
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Account.php (Model)
class Account extends Model
{
public function profile()
{
return $this->belongsTo(Profile::class);
}
}
Query Example:
$user = User::find(1);
$account = $user->account;
6. Has Many Through
A has-many-through relationship is used when a model has multiple related models through an intermediate model.
Example:
A User has many Payments, but the relation is through Orders.
Database Structure:
users table: id
orders table: id, user_id
payments table: id, order_id
// User.php (Model)
class User extends Model
{
public function payments()
{
return $this->hasManyThrough(Payment::class, Order::class);
}
}
// Order.php (Model)
class Order extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
// Payment.php (Model)
class Payment extends Model
{
public function order()
{
return $this->belongsTo(Order::class);
}
}
Query Example:
$user = User::find(1);
$payments = $user->payments; // Fetch all payments made by the user through orders
Laravel follows multiple design patterns to ensure a structured and efficient development process. Below are the key design patterns used in Laravel:
a) Factory Pattern
b) Singleton Pattern
a) Facade Pattern
b) Adapter Pattern
These patterns manage object communication and behavior.
a) Strategy Pattern
Example: Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required|min:8' ]);
b) Observer Pattern
c) Command Pattern
Example: php artisan make:command CustomCommand
d) Repository Pattern
a) Model-View-Controller (MVC) Pattern
b) Dependency Injection Pattern
Middleware in Laravel acts as a bridge between a request and a response, allowing you to filter and modify HTTP requests before they reach your application's routes or controllers.
Define Middleware
To apply middleware to every request, add it to the app/Http/Kernel.php file inside the $middleware array.
To use middleware for specific routes, add it inside $routeMiddleware in Kernel.php
Types of Middleware
Laravel provides a powerful caching system that helps improve application performance by storing frequently accessed data in a fast-access storage system like file system, database, Redis, or Memcached. Caching reduces database queries, speeds up request responses, and enhances the overall efficiency of the application.
Laravel supports multiple cache drivers, which can be configured in the .env file using the CACHE_DRIVER key:
CACHE_DRIVER=file # Default is file-based caching
Supported cache drivers:
In Laravel, event listeners are used to handle events in an application.
The event-listener mechanism follows the Observer Pattern, where an event is fired, and listeners respond to it asynchronously.
How Events and Listeners Work in Laravel
Laravel's event-listener system provides a clean way to decouple various parts of the application. It is useful for:
public/index.php (autoloader.php, load files provided by the composer)
==>
bootstrap/app.php (created instance of laravel application)
==>
app/http/kernal.php (loads middlewares)
==>
config/app.php (receive request to load all service providers mentioned)
==>
routes
Reverse routing in Laravel refers to generating URLs for named routes using route names instead of hardcoding URLs.
Example:
Route::get('/home', [HomeController::class, 'index'])->name('home');
An accessor is used to change the value when you get it from the database.
Example:
If the user's name in the database is john
, you can use an accessor to show it as John
.
Now, when you do:
A mutator is used to change the value before saving it to the database.
Example:
If you want to save the name always in lowercase, use a mutator.
Now, when you do:
It will store john doe
in the database.
Feature | When it works | Purpose |
---|---|---|
Accessor | When getting data | Format before displaying |
Mutator | When setting data | Format before saving |
A micro framework is a minimalistic web framework that provides only the essential features to build small or lightweight web applications or APIs — usually without extras like authentication, form validation, or templating.
They are ideal for:
APIs
Small services
Lightweight applications
Rapid prototyping
Lightweight and fast
Minimal built-in features
Easy to learn and use
Flexible and extensible via plugins or third-party libraries
No heavy architecture or structure
Framework | Language | Description |
---|---|---|
Lumen | PHP | Micro version of Laravel for building APIs |
Slim | PHP | Simple PHP micro framework |
Silex (Deprecated) | PHP | Based on Symfony components |
Flask | Python | Lightweight and simple web framework |
Express.js | Node.js | Fast and minimalist for building RESTful APIs |
1. Create the Command
Use Artisan to generate a new command class:
php artisan make:command MyCustomCommand
This will create a file in:
app/Console/Commands/MyCustomCommand.php
2. Edit the Command File
Open MyCustomCommand.php
and modify it like this:
3. Register the Command
Open app/Console/Kernel.php
and register the command in the $commands
array:
protected $commands = [ \App\Console\Commands\MyCustomCommand::class, ];
4. Run the Command
Use Artisan to run it:
php artisan greet:user John
Output:
Hello, John! Welcome to Laravel.