Kritim Yantra
Mar 12, 2025
Laravel 12, released in February 2025, focuses on maintenance, updated dependencies, and introduces new starter kits for React, Vue, and Livewire with minimal new features. Advanced interview questions now cover topics like eager loading, query scopes, soft deletes, event handling, and API authentication—critical areas for experienced developers.
This guide provides detailed explanations, code examples, and a comparative analysis of advanced topics to help you prepare for interviews and build scalable applications.
Laravel 12 was released on February 24, 2025, as a maintenance release that emphasizes stability and compatibility with PHP 8.2 and 8.3. With new starter kits for modern front-end frameworks, Laravel 12 makes it easier for developers to build robust applications without introducing breaking changes.
Question: Explain the difference between eager loading and lazy loading in Eloquent, and when would you use each?
Answer: Lazy Loading (the default) loads related data only when you access it, which can lead to the N+1 query problem. For example:
<?php
$users = User::all();
foreach ($users as $user) {
// Each loop triggers a new query to fetch posts
echo $user->posts->count();
}
Eager Loading, using with()
, fetches related data in fewer queries:
<?php
$users = User::with('posts')->get();
foreach ($users as $user) {
echo $user->posts->count(); // No additional queries here
}
Use lazy loading for single records and eager loading when dealing with multiple records to reduce query count.
Question: What are query scopes in Eloquent, and how do global scopes differ from regular scopes?
Answer: Local (or regular) scopes are reusable query constraints defined in a model and applied explicitly. For example:
<?php
// In User.php model
public function scopeActive($query) {
return $query->where('is_active', true);
}
// Usage:
$activeUsers = User::active()->get();
Global scopes automatically apply to all queries for a model. For example, a tenant scope:
<?php
class TenantScope implements Scope {
public function apply(Builder $builder, Model $model) {
$builder->where('tenant_id', auth()->user()->tenant_id);
}
}
// In User.php model's booted method:
protected static function booted() {
static::addGlobalScope(new TenantScope);
}
Local scopes are for optional filters; global scopes are automatically applied for all queries.
Question: How does soft deleting work in Eloquent, and how can you restore a soft-deleted record?
Answer: Soft deletes mark records as deleted by setting a deleted_at
timestamp without permanently removing the data.
Enable soft deletes in a model:
<?php
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
}
In the migration, add the soft deletes column:
Schema::table('users', function (Blueprint $table) {
$table->softDeletes(); // Adds a 'deleted_at' column
});
To restore a soft-deleted record:
<?php
$user = User::onlyTrashed()->where('id', 1)->first();
$user->restore();
Use forceDelete()
to permanently delete a record.
Question: Explain how to set up an event listener in Laravel to handle a specific event.
Answer: Create an event and a listener using Artisan, then dispatch the event.
Example:
<!-- Create the event -->
php artisan make:event OrderShipped
// In OrderShipped.php
class OrderShipped {
public function __construct(public Order $order) {}
}
<!-- Create the listener -->
php artisan make:listener SendShipmentNotification
// In SendShipmentNotification.php
class SendShipmentNotification {
public function handle(OrderShipped $event) {
$event->order->user->notify(new ShipmentNotification());
}
}
Dispatch the event with:
event(new OrderShipped($order));
Question: How do you create a custom Artisan command in Laravel?
Answer: Generate a command using Artisan, define its signature and logic in the handle
method, and then run it from the CLI.
<?php
// Generate command:
php artisan make:command BackupDatabase
// In BackupDatabase.php
class BackupDatabase extends Command {
protected $signature = 'db:backup';
protected $description = 'Backup the database';
public function handle() {
$this->info('Backing up database...');
// Backup logic here
$this->info('Backup completed!');
}
}
Run the command with:
php artisan db:backup
Question: What is middleware, and how do you create custom middleware?
Answer: Middleware intercepts HTTP requests. Create custom middleware with php artisan make:middleware EnsureIsAdmin
, implement the handle
method, and apply it to routes.
<?php
// In EnsureIsAdmin.php
class EnsureIsAdmin {
public function handle($request, Closure $next) {
if (!auth()->user()->isAdmin()) {
abort(403, 'Unauthorized');
}
return $next($request);
}
}
Question: What role do service providers play in a Laravel application?
Answer: Service providers bootstrap your application by registering and configuring services. Create a provider with php artisan make:provider PaymentServiceProvider
, bind interfaces in the register
method, and perform bootstrapping actions in boot
.
<?php
// In PaymentServiceProvider.php
class PaymentServiceProvider extends ServiceProvider {
public function register() {
$this->app->bind(PaymentGateway::class, StripeGateway::class);
}
public function boot() {
// Bootstrapping actions here
}
}
Register this provider in bootstrap/providers.php
.
Question: How does dependency injection work in Laravel?
Answer: Laravel's service container automatically resolves dependencies. When a controller's constructor is type-hinted, Laravel injects the appropriate object. For example:
<?php
class UserController extends Controller {
public function __construct(private UserRepository $users) { }
public function show($id) {
return $this->users->find($id);
}
}
Bind an interface using:
app()->bind(UserRepositoryInterface::class, EloquentUserRepository::class);
Question: What are the differences between unit tests and feature tests in Laravel?
Answer: Unit tests focus on individual components (e.g., a model method), while feature tests simulate HTTP requests to test complete features. For example:
<?php
// Unit Test
class CalculatorTest extends TestCase {
public function test_adds_numbers() {
$this->assertEquals(4, Calculator::add(2, 2));
}
}
// Feature Test
class LoginTest extends TestCase {
public function test_user_can_login() {
$response = $this->post('/login', [
'email' => 'user@example.com',
'password' => 'password',
]);
$response->assertRedirect('/dashboard');
}
}
Run tests with:
php artisan test
Question: Explain how to set up a job and process it in Laravel.
Answer: Create a job with php artisan make:job ProcessPodcast
, implement its handle()
method, and dispatch it using ProcessPodcast::dispatch($podcast);
. Process jobs with:
php artisan queue:work redis
Question: What is Passport and how does it help with API authentication?
Answer: Passport provides a full OAuth2 server implementation for API authentication using JWT tokens. Install it, run migrations, create clients with php artisan passport:install
, and protect routes with the auth:api
middleware.
composer require laravel/passport
php artisan migrate
php artisan passport:install
Question: How does broadcasting work in Laravel?
Answer: Broadcasting sends real-time updates to clients. Create events that implement ShouldBroadcast
, fire them using event(new EventName($data));
, and subscribe on the client side with Laravel Echo.
<?php
class OrderStatusUpdated implements ShouldBroadcast {
public function __construct(public Order $order) { }
public function broadcastOn() {
return new Channel('orders.' . $this->order->id);
}
}
Question: How do you create custom Blade directives?
Answer: In a service provider’s boot method, use Blade::directive
to define custom directives.
<?php
Blade::directive('datetime', function ($expression) {
return "format('m/d/Y H:i'); ?>";
});
Use it in Blade:
@datetime($order->created_at)
Question: How does file storage work in Laravel, and what are disks?
Answer: File storage uses the Storage facade, and disks are defined in config/filesystems.php
. Use methods like Storage::disk('s3')->put()
to upload files.
<?php
$url = Storage::disk('s3')->url('avatars/1.jpg');
Question: Explain how to send notifications and what channels are available.
Answer: Create notifications using php artisan make:notification
, define channels (mail, database, Slack) in the via()
method, and send them with $user->notify(new NotificationClass());
.
<?php
class InvoicePaid extends Notification {
public function via($notifiable) {
return ['mail', 'database'];
}
public function toMail($notifiable) {
return (new MailMessage)
->line('Your invoice has been paid!');
}
public function toArray($notifiable) {
return ['amount' => 100];
}
}
The table below summarizes key aspects of these advanced topics:
Topic | Key Feature | Use Case Example |
---|---|---|
Eager Loading | Preloads related data | Fetching user posts efficiently |
Query Scopes | Reusable query logic | Filtering published posts |
Soft Deletes | Marks records as deleted | Recovering deleted orders |
Event Handling | Decouples event reactions | Sending welcome emails |
Artisan Commands | Automates tasks | Batch processing data |
Middleware | Filters HTTP requests | Checking admin access |
Service Providers | Manages bootstrapping and dependency bindings | Registering payment gateways |
Dependency Injection | Decouples classes via the service container | Injecting services in controllers |
Testing | Ensures code reliability | Unit and feature tests for login functionality |
Queueing | Processes tasks asynchronously | Sending emails in background |
Passport | API authentication | Securing API endpoints |
Broadcasting | Real-time updates | Live chat notifications |
Blade Directives | Extends templating functionality | Custom greetings in views |
File Storage | Unified file handling | Uploading user images |
Notifications | Multi-channel alerts | Email and database notifications |
Mastering these Laravel 12 concepts and advanced topics not only prepares you for technical interviews but also ensures that your applications are efficient, scalable, and easy to maintain. Laravel 12 emphasizes stability and compatibility while introducing new starter kits for modern front-end frameworks. Understanding how to optimize queries with eager loading, handle dependencies using the service container, manage background tasks with queues, and secure your API with Passport can significantly enhance your development process.
Happy coding!
No comments yet. Be the first to comment!
Please log in to post a comment:
Continue with Google