Loading...

Interview Q&A – Crack Your Next Interview

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?

  • Dependency Injection: Automatically injects dependencies into classes.
  • Binding Interfaces to Implementations: Helps in achieving loose coupling.
  • Singleton Management: Ensures only one instance of a service is created.
  • Lazy Loading: Resolves dependencies only when required, optimizing performance.

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

  1. Dependency Injection: The User model is injected via the controller’s constructor, making it accessible in all methods.
  2. Reusability: Instead of calling User::all() multiple times, we use $this->user->all(), improving code maintainability.
  3. Service Container: Laravel automatically resolves the User model when the controller is initialized.

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.

Key Features of Eloquent ORM

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:

1. Creational Design Patterns

a) Factory Pattern

  • Used to create objects without exposing the instantiation logic.
  • Laravel's factory() method helps generate model instances for testing and seeding.

b) Singleton Pattern

  • Ensures that only one instance of a class is created.
  • Laravel uses singletons for services like database connections, configuration, and caching.

2. Structural Design Patterns

a) Facade Pattern

  • Provides a static interface to classes in Laravel’s service container.
  • Simplifies complex class dependencies.

b) Adapter Pattern

  • Allows classes with incompatible interfaces to work together.
  • Laravel uses adapters in database configurations, cache drivers, and queue drivers.
    Example: Laravel’s database supports multiple drivers like MySQL, PostgreSQL, and SQLite using the adapter pattern.

3. Behavioral Design Patterns

These patterns manage object communication and behavior.

a) Strategy Pattern

  • Defines a family of algorithms, encapsulates them, and makes them interchangeable.
  • Laravel uses this in validation rules, authentication, and payment gateways.

Example: Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required|min:8' ]);

b) Observer Pattern

  • Used for event-driven programming where objects can subscribe to an event.
  • Laravel’s Observer class is used for listening to model events.

c) Command Pattern

  • Encapsulates a request as an object, allowing parameterization of clients with different requests.
  • Laravel uses this in Artisan commands.

Example: php artisan make:command CustomCommand

d) Repository Pattern

  • Abstracts data layer, making it independent of the database.

4. Architectural Pattern in Laravel

a) Model-View-Controller (MVC) Pattern

b) Dependency Injection Pattern

  • Avoids hard dependencies and improves testability.
    Example: 
    public function __construct(UserRepository $userRepository) 

          $this->userRepository = $userRepository; 
    }

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

1. Global Middleware

To apply middleware to every request, add it to the app/Http/Kernel.php file inside the $middleware array.

2. Route Middleware

To use middleware for specific routes, add it inside $routeMiddleware in Kernel.php

Types of Middleware

  • Authentication Middleware: Ensures users are logged in. (auth)
  • Throttle Middleware: Limits API request rate. (throttle:60,1)
  • Custom Middleware: You can create and register your own.

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:

  • File (file) – Stores cached data in storage/framework/cache
  • Database (database) – Uses a database table
  • Redis (redis) – Uses Redis for caching (recommended for performance)
  • Memcached (memcached) – Uses Memcached for high-speed caching
  • Array (array) – Stores cache data in memory for the current request (not persistent)
  • APC/APCu (apc) – Uses APC/APCu cache (requires APC extension)
  • DynamoDB (dynamodb) – Uses AWS DynamoDB for distributed caching

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

  1. Event is Fired – An event represents an action or occurrence in the application (e.g., user registration).
  2. Listeners Handle Events – A listener is a class that responds to the event (e.g., sending a welcome email after registration).

Laravel's event-listener system provides a clean way to decouple various parts of the application. It is useful for:

  • Sending notifications
  • Logging activities
  • Executing background jobs

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.

// In app/Models/User.php
public function getNameAttribute($value)
{
    return ucfirst($value); // Makes first letter uppercase
}

Now, when you do:

$user = User::find(1);
echo $user->name; // Outputs: John

 

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.

// In app/Models/User.php
public function setNameAttribute($value)
{
    $this->attributes['name'] = strtolower($value);
}

Now, when you do:

$user = new User();
$user->name = 'John Doe';
$user->save();

It will store john doe in the database.

✅ Final Summary:

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


✅ Key Characteristics of Micro Frameworks:

  • 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


🔸 Examples of Micro Frameworks:

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:

namespace App\Console\Commands;

use Illuminate\Console\Command;

class MyCustomCommand extends Command
{
    // The name used to run the command (e.g., php artisan greet:user)
    protected $signature = 'greet:user {name}';

    // The description shown in php artisan list
    protected $description = 'Greet a user by their name';

    public function handle()
    {
        $name = $this->argument('name');
        $this->info("Hello, $name! Welcome to Laravel.");
    }
}

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.