đą Basic Laravel Interview Questions & Answers
1. What is Laravel? Why do we use it?
Answer:
Laravel is a PHP framework based on MVC (Model-View-Controller) architecture. It provides elegant syntax, built-in features like routing, authentication, ORM, and caching that help developers build web applications faster and with less effort.
2. What are the main features of Laravel?
Answer:
-
Eloquent ORM (database handling)
-
Blade template engine
-
Artisan CLI
-
Routing system
-
Middleware
-
Authentication and Authorization
-
Migrations and Seeders
-
Task scheduling & Queues
-
RESTful API support
-
Built-in Security (CSRF, XSS protection, encryption)
3. What is MVC architecture in Laravel?
Answer:
-
Model → Handles data and database logic.
-
View → Displays data (UI).
-
Controller → Handles user requests, processes data via Model, and returns responses via View.
Laravel follows MVC to separate concerns and keep code organized.
4. What is Artisan in Laravel?
Answer:
Artisan is Laravel’s command-line tool. It helps automate repetitive tasks like creating controllers, models, migrations, seeding, clearing cache, etc.
Example:
php artisan make:controller UserController
php artisan migrate
5. What are Service Providers in Laravel?
Answer:
Service providers are the central place of Laravel application bootstrapping. They register services, bindings, and event listeners. For example, AppServiceProvider
, AuthServiceProvider
.
6. What is Middleware in Laravel?
Answer:
Middleware is a filter for HTTP requests.
-
Example:
auth
middleware checks if a user is logged in before accessing certain routes. -
We can also create custom middleware for logging, role-checking, etc.
7. Explain the difference between GET, POST, PUT, and DELETE in Laravel routes.
Answer:
-
GET
→ Retrieve data (e.g., view a page). -
POST
→ Submit new data (e.g., create user). -
PUT
→ Update existing data (e.g., update profile). -
DELETE
→ Delete existing data (e.g., delete record).
Example:
Route::get('/users', 'UserController@index');
Route::post('/users', 'UserController@store');
Route::put('/users/{id}', 'UserController@update');
Route::delete('/users/{id}', 'UserController@destroy');
8. What is the difference between Session and Cache?
Answer:
-
Session → Stores user-related temporary data (e.g., login info, shopping cart).
-
Cache → Stores frequently accessed data to improve performance (e.g., query results, API responses).
9. How does Laravel handle security?
Answer:
-
CSRF Protection → Prevents cross-site request forgery using
_token
. -
XSS Protection → Escapes output in Blade
{{ $data }}
. -
SQL Injection Protection → Eloquent & Query Builder use prepared statements.
-
Password Hashing →
bcrypt
andargon2
.
10. How do you install Laravel?
Answer:
-
Install Composer.
-
Run command:
composer create-project laravel/laravel myApp
or
laravel new myApp
Great đ Let’s continue with the Intermediate Level Laravel Interview Questions & Answers (11–20).
⚡ Intermediate Laravel Interview Questions & Answers
11. What is Eloquent ORM?
Answer:
Eloquent is Laravel’s built-in ORM (Object-Relational Mapper). It allows interaction with the database using models instead of raw SQL queries.
Example:
$users = User::all(); // Select * from users
$user = User::find(1); // Select * from users where id = 1
12. What are the differences between hasOne
, hasMany
, belongsTo
, and belongsToMany
relationships?
Answer:
-
hasOne → One-to-One relationship. (User → Profile)
-
hasMany → One-to-Many relationship. (User → Posts)
-
belongsTo → Inverse of
hasOne
/hasMany
. (Post → User) -
belongsToMany → Many-to-Many relationship. (User ↔ Roles)
Example:
// User hasOne Profile
public function profile() { return $this->hasOne(Profile::class); }
// User hasMany Posts
public function posts() { return $this->hasMany(Post::class); }
// Post belongsTo User
public function user() { return $this->belongsTo(User::class); }
// User belongsToMany Roles
public function roles() { return $this->belongsToMany(Role::class); }
13. What are Migrations in Laravel? Why do we use them?
Answer:
Migrations are version control for databases. They allow us to create, update, and share database structures with code instead of manual SQL.
Example:
php artisan make:migration create_users_table
php artisan migrate
14. What is the difference between Query Builder and Eloquent?
Answer:
-
Query Builder → Works with raw SQL queries, lightweight, faster for complex queries.
-
Eloquent → Object-oriented, works with models, easier to use but slightly slower.
Example:
// Query Builder
$users = DB::table('users')->where('status', 1)->get();
// Eloquent
$users = User::where('status', 1)->get();
15. How do you implement validation in Laravel?
Answer:
Using validate()
in controllers or FormRequest
.
Example:
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
'password' => 'required|min:6'
]);
16. What are Laravel Facades?
Answer:
Facades provide a static interface to classes inside the service container.
Example:
Cache::put('key', 'value', 600); // Instead of dependency injection
Common facades: DB
, Cache
, Auth
, Route
, Storage
.
17. What are Accessors and Mutators in Eloquent?
Answer:
-
Accessor → Format attribute when retrieving.
-
Mutator → Modify attribute before saving.
Example:
// Accessor
public function getNameAttribute($value) {
return ucfirst($value);
}
// Mutator
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
18. What is the difference between Guard and Provider in Laravel Authentication?
Answer:
-
Guard → Defines how users are authenticated (session, token, API).
-
Provider → Defines how users are retrieved from the database.
Example: In config/auth.php
:
'guards' => [
'web' => ['driver' => 'session', 'provider' => 'users'],
'api' => ['driver' => 'token', 'provider' => 'users'],
],
'providers' => [
'users' => ['driver' => 'eloquent', 'model' => App\Models\User::class],
]
19. What are Laravel Queues and why do we use them?
Answer:
Queues allow us to run long tasks (emails, notifications, reports) in the background instead of blocking the request.
Example:
dispatch(new SendEmailJob($user));
Queue workers:
php artisan queue:work
20. What is Dependency Injection in Laravel?
Answer:
Dependency Injection (DI) is a design pattern where Laravel automatically provides class dependencies instead of manually creating them.
Example:
class UserController extends Controller {
public function __construct(UserRepository $userRepo) {
$this->userRepo = $userRepo; // Automatically injected
}
}
Perfect đ Now let’s move on to the Advanced Level Laravel Interview Questions & Answers (21–30).
đ Advanced Laravel Interview Questions & Answers
21. What is the Repository Pattern in Laravel?
Answer:
Repository Pattern is used to abstract the data layer. Instead of directly using Eloquent in controllers, we use repositories to separate database logic from business logic.
-
Advantage → Cleaner code, easy to switch database/storage.
Example:
interface UserRepository {
public function getAll();
}
class EloquentUserRepository implements UserRepository {
public function getAll() {
return User::all();
}
}
22. How do you handle events and listeners in Laravel?
Answer:
Events allow you to subscribe and listen for actions in your application.
Example:
php artisan make:event OrderPlaced
php artisan make:listener SendOrderEmail --event=OrderPlaced
-
Event →
OrderPlaced
fires when an order is created. -
Listener →
SendOrderEmail
sends an email after the event.
23. What are Laravel Jobs and Workers?
Answer:
-
Job → Represents a unit of work (e.g., sending email, generating report).
-
Worker → A background process that executes queued jobs.
Example:
php artisan make:job SendEmailJob
dispatch(new SendEmailJob($user));
php artisan queue:work
24. How does Laravel handle caching? Name different cache drivers.
Answer:
Laravel provides unified API for caching.
Supported drivers:
-
file
-
database
-
redis
-
memcached
-
array
Example:
Cache::put('key', 'value', 600);
$value = Cache::get('key');
25. What is the difference between Laravel Passport and Laravel Sanctum?
Answer:
-
Passport → Full OAuth2 authentication system. Best for large apps, multiple clients, third-party integrations.
-
Sanctum → Lightweight API authentication using tokens/cookies. Best for single-page apps (SPA) or simple APIs.
26. How do you implement API rate limiting in Laravel?
Answer:
Use throttle middleware.
Example in routes/api.php
:
Route::middleware('throttle:60,1')->get('/user', function () {
return auth()->user();
});
This means: max 60 requests per minute per user/IP.
27. What are Laravel Policies and Gates?
Answer:
-
Gates → Closures that determine if a user is authorized to perform an action.
-
Policies → Classes that organize authorization logic around models.
Example (Gate):
Gate::define('update-post', function ($user, $post) {
return $user->id === $post->user_id;
});
Example (Policy):
php artisan make:policy PostPolicy
28. How do you use Laravel Observers?
Answer:
Observers allow you to listen to model events (creating, updating, deleting).
Example:
php artisan make:observer UserObserver --model=User
In UserObserver.php
:
public function created(User $user) {
Log::info('New user created: ' . $user->email);
}
Register in AppServiceProvider
:
User::observe(UserObserver::class);
29. What is the difference between composer dump-autoload
and php artisan optimize
?
Answer:
-
composer dump-autoload
→ Rebuilds class map for autoloading (loads new classes). -
php artisan optimize
→ (In older versions) optimized config, routes, and class loading.
đ In Laravel 8+,optimize
command is removed because auto-optimization happens automatically.
30. How do you manage multiple database connections in Laravel?
Answer:
Define multiple connections in config/database.php
:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'database' => env('DB_DATABASE', 'db1'),
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST2', '127.0.0.1'),
'database' => env('DB_DATABASE2', 'db2'),
],
Use connection:
$users = DB::connection('mysql2')->table('users')->get();
Perfect đ Let’s finish strong with the Expert / Practical Laravel Interview Questions & Answers (31–40).
đĨ Expert / Practical Laravel Interview Questions & Answers
31. How do you implement a composite key in Laravel models?
Answer:
Laravel doesn’t support composite primary keys directly.
Options:
-
Use raw queries or Query Builder.
-
Override
getKeyName()
and primary key handling. -
Use a community package like
laravel-composite-key
.
Example (manual approach):
protected $primaryKey = ['order_id', 'product_id'];
public $incrementing = false;
But usually we handle it via unique index in migrations instead of composite primary key.
32. How do you optimize Laravel application performance?
Answer:
-
Use config, route, and view caching:
php artisan config:cache php artisan route:cache php artisan view:cache
-
Use queues for heavy tasks.
-
Optimize database queries (avoid N+1).
-
Use Eager Loading in Eloquent.
-
Use Redis/Memcached for caching & sessions.
-
Use Octane (Swoole/RoadRunner) for faster execution.
-
Optimize assets with Laravel Mix/Vite.
33. Explain Laravel’s Service Container.
Answer:
The Service Container is a dependency injection container. It manages class dependencies and automatically injects them when needed.
Example:
app()->bind('PaymentGateway', function () {
return new StripePaymentGateway();
});
Now, whenever you type-hint PaymentGateway
, Laravel injects StripePaymentGateway
.
34. How do you schedule tasks in Laravel?
Answer:
Laravel uses the schedule()
method in App\Console\Kernel.php
.
Example:
protected function schedule(Schedule $schedule)
{
$schedule->command('emails:send')->dailyAt('9:00');
}
Then set CRON job:
* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1
35. What is the difference between load()
, with()
, and lazyload()
in Eloquent?
Answer:
-
with() → Eager loads relationship at query time.
-
load() → Eager loads relationship after query execution.
-
lazyload() → Loads relationship only when accessed.
Example:
$users = User::with('posts')->get(); // with()
$user = User::find(1);
$user->load('posts'); // load()
$user->posts; // lazy load
36. How do you debug queries in Laravel?
Answer:
-
Enable query logging:
DB::enableQueryLog();
$users = DB::table('users')->get();
dd(DB::getQueryLog());
-
Use
toSql()
:
$query = User::where('status', 1);
dd($query->toSql());
-
Use Laravel Telescope or Debugbar package.
37. How do you prevent N+1 query problems in Laravel?
Answer:
Use Eager Loading.
Bad (N+1 problem):
$users = User::all();
foreach ($users as $user) {
echo $user->posts->count();
}
Good (with eager loading):
$users = User::with('posts')->get();
38. How do you use Laravel’s Broadcasting system?
Answer:
Broadcasting allows sending real-time events to clients (like WebSockets).
Steps:
-
Configure driver in
.env
→BROADCAST_DRIVER=pusher
(or redis). -
Create event:
php artisan make:event OrderShipped
-
Implement
ShouldBroadcast
:class OrderShipped implements ShouldBroadcast { public $order; public function __construct(Order $order) { $this->order = $order; } public function broadcastOn() { return ['orders']; } }
-
Listen from frontend using Laravel Echo.
39. How do you secure an API built in Laravel?
Answer:
-
Use Laravel Sanctum/Passport for authentication.
-
Add rate limiting with throttle middleware.
-
Use CSRF protection (if session-based).
-
Validate inputs using Form Requests.
-
Use HTTPS (SSL).
-
Hide sensitive keys in
.env
. -
Return consistent JSON responses with proper status codes.
40. How would you scale a Laravel application for millions of users?
Answer:
-
Use Load Balancers (Nginx/HAProxy).
-
Horizontal scaling: multiple servers running Laravel.
-
Use Redis/Memcached for caching & queues.
-
Optimize DB (indexes, read/write splitting, replication).
-
Use CDN for static assets.
-
Use Laravel Horizon to manage queues.
-
Use Octane for performance.
-
Containerize app with Docker/Kubernetes.
No comments:
Post a Comment