Laravel Interview Questions

Basic Laravel Interview Questions

Q1: What is Laravel? Why is it used?
A: Laravel is an open-source PHP framework designed for web application development. It follows the MVC (Model-View-Controller) architecture, offering tools and features like routing, authentication, and database migrations to make development faster and more efficient.

Q2: What are service providers in Laravel?
A: Service providers are the central place to configure applications. They bootstrap various components like routing, events, and middleware. They are stored in the app/Providers directory, and you can register them in the config/app.php file.

Q3: What is Composer in Laravel?
A: Composer is a dependency management tool for PHP. Laravel uses Composer to manage its dependencies and libraries, making it easy to install, update, and manage third-party packages.

Q4: How does routing work in Laravel?
A: Laravel routes are defined in files stored in the routes directory, such as web.php for web routes and api.php for API routes. You can define routes using closures or controller actions.
Example:
Route::get(‘/home’, [HomeController::class, ‘index’]);

Q5: What is Eloquent ORM?
A: Eloquent is Laravel’s built-in Object-Relational Mapping (ORM) system. It provides an intuitive and elegant way to interact with databases using models.
Example:
$users = User::all();

Intermediate Laravel Interview Questions

Q6: How does middleware work in Laravel?
A: Middleware filters HTTP requests entering the application. Common examples include authentication and logging. Middleware can be applied globally, on specific routes, or groups.
Example:
Route::middleware([‘auth’])->group(function () {
Route::get(‘/dashboard’, [DashboardController::class, ‘index’]);
});

Q7: What are the different types of relationships in Eloquent?
A: Laravel supports several types of relationships:

  • One to One: hasOne() and belongsTo()
  • One to Many: hasMany() and belongsTo()
  • Many to Many: belongsToMany()
  • Has Many Through: hasManyThrough()
  • Polymorphic Relationships

Q8: What is the purpose of migrations in Laravel?
A: Migrations are used to version-control database schema. They allow developers to create and modify tables in a structured and consistent manner. Example of creating a migration:
// php artisan make:migration create_users_table

Q9: How does dependency injection work in Laravel?
A: Laravel’s service container manages dependency injection by resolving class dependencies automatically. You can inject dependencies into a controller constructor or methods.
Example:
public function __construct(UserRepository $userRepo)
{
$this->userRepo = $userRepo;
}

Q10: What is the purpose of queues in Laravel?
A: Queues in Laravel allow you to defer the execution of time-consuming tasks like sending emails or processing video uploads. Laravel supports several queue drivers like database, redis, and sqs.
Example:
dispatch(new SendEmailJob($user));

Advanced Laravel Interview Questions

Q11: How can you implement event broadcasting in Laravel?
A: Event broadcasting allows server-side events to be sent to the client-side in real-time. Laravel uses Pusher, Redis, or other WebSocket implementations for broadcasting. Example:

  1. Create an event: php artisan make:event UserRegistered
  2. Add the ShouldBroadcast interface to broadcast the event.

Q12: What are Laravel Nova and Laravel Horizon?
A:

  • Laravel Nova: A beautiful admin panel for managing resources.
  • Laravel Horizon: A dashboard for monitoring and managing queues.

Q13: What is the difference between lazy loading and eager loading in Laravel?
A:

  • Lazy Loading: Loads relationships when accessed. Example: $post->comments.
  • Eager Loading: Preloads relationships to reduce queries. Example: $posts = Post::with('comments')->get();

Q14: How do you secure Laravel applications?
A: Key security practices include:

  • Use HTTPS for all routes.
  • Validate and sanitize user inputs.
  • Prevent SQL Injection using Eloquent or query bindings.
  • Use csrf_field() for CSRF protection.
  • Configure proper access controls and roles.

Q15: How does Laravel handle API rate limiting?
A: Laravel provides built-in support for API rate limiting using the RateLimiter facade. You can define rate limits in RouteServiceProvider.
Example:
RateLimiter::for(‘api’, function (Request $request) {
return Limit::perMinute(60);
});

Junior/Entry Level (16-25)

Q16: What is a “Blade” in Laravel?

A: Blade is Laravel’s powerful templating engine. Unlike other PHP templating engines, Blade allows you to use plain PHP in your templates and compiles them into cached PHP code for performance. It uses .blade.php extensions.

Q17: What is the purpose of the .env file?

A: The .env file stores configuration variables for different environments (local, staging, production). It holds sensitive data like database credentials, API keys, and app secrets, ensuring they aren’t hard-coded into the source control.

Q18: What are “Requests” in Laravel?

A: The Illuminate\Http\Request class provides a way to interact with the current HTTP request being handled by your application. You can retrieve input, cookies, and files uploaded with the request.

Q19: How do you generate a controller via Artisan?

A: You use the command: php artisan make:controller ControllerName. Adding the --resource flag will pre-fill it with standard CRUD methods (index, create, store, etc.).

Q20: What is the difference between {{ $var }} and {!! $var !!} in Blade?

A: {{ $var }} automatically escapes HTML entities using PHP’s htmlspecialchars to prevent XSS attacks. {!! $var !!}outputs the raw data, which is useful when you want to render HTML stored in a variable.

Q21: What are “Named Routes”?

A: Named routes allow you to refer to a route by a specific name rather than the URL path. This makes it easier to generate URLs or redirects.

Example: Route::get('/user/profile', [ProfileController::class, 'show'])->name('profile');

Q22: What is the “public” folder used for?

A: The public folder is the entry point for all requests entering the application (via index.php). It also houses assets like images, JavaScript, and CSS.

Q23: How do you run migrations in Laravel?

A: Use php artisan migrate. To undo the last migration, use php artisan migrate:rollback.

Q24: What is a “Faker” library?

A: Faker is a PHP library used by Laravel’s Model Factories to generate fake data for testing or seeding databases with realistic-looking information.

Q25: What are “Seeders”?

A: Seeders are classes used to populate the database with initial or dummy data. They are stored in database/seedersand executed using php artisan db:seed.


Mid-Level (26-40)

Q26: What is the Service Container?

A: The Service Container is a powerful tool for managing class dependencies and performing dependency injection. It is the “glue” that holds Laravel together.

Q27: What are “Facades” in Laravel?

A: Facades provide a “static” interface to classes that are available in the application’s service container. They serve as a proxy for accessing underlying implementations.

Example: Cache::get('key');

Q28: What is the difference between a “Mailable” and a “Notification”?

A: A Mailable is specifically for sending emails using a Blade template. A Notification is more versatile; it can send messages via multiple channels like Email, SMS, Slack, or Database.

Q29: What are “Accessors” and “Mutators”?

A:

  • Accessors: Format Eloquent attribute values when you retrieve them (e.g., capitalizing a name).
  • Mutators: Format values before they are saved to the database (e.g., hashing a password).

Q30: What is the “Mass Assignment” vulnerability?

A: It occurs when a user sends unexpected HTTP parameters that change columns in your database you didn’t intend to be changed (like an is_admin flag). Laravel prevents this by requiring you to define $fillable or $guarded properties on your models.

Q31: What are “Eloquent Collections”?

A: All multi-result sets returned by Eloquent are instances of the Illuminate\Database\Eloquent\Collection object. This object extends the base Laravel Collection and provides helpful methods for mapping, filtering, and reducing data.

Q32: What is the purpose of “Validation” in Laravel?

A: Laravel provides several ways to validate incoming data, usually via the validate method in controllers or Form Request classes, which house validation logic separately.

Q33: How do you handle “Soft Deletes”?

A: By using the SoftDeletes trait on a model. Instead of removing the record from the database, it sets a deleted_attimestamp. You can retrieve these using withTrashed().

Q34: What are “Model Observers”?

A: Observers are used to group event listeners for a specific model. They listen for events like creatingupdated, or deleted to perform actions automatically.

Q35: Explain “Route Grouping”.

A: Route groups allow you to share route attributes, such as middleware or namespaces, across a large number of routes without needing to define those attributes on every single route.

Q36: What is the difference between sync() and attach() in many-to-many relationships?

A: attach() simply adds a record to the pivot table. sync() accepts an array of IDs and ensures only those IDs exist in the pivot table, deleting any others.

Q37: What is “Tinker” in Laravel?

A: Laravel Tinker is a REPL (Read-Eval-Print Loop) powered by the PsySH package. It allows you to interact with your entire Laravel application from the command line.

Q38: How do you handle file uploads in Laravel?

A: You can use the store method on a file instance from the request.

Example: $path = $request->file('avatar')->store('avatars');

Q39: What are “API Resources”?

A: API Resources act as a transformation layer between your Eloquent models and the JSON responses that are actually returned to your application’s users.

Q40: What is “Artisan”?

A: Artisan is the built-in command-line interface for Laravel. It provides helpful commands for migrations, testing, and generating boilerplate code.


Advanced Level (41-50)

Q41: What is “Dependency Inversion” in the context of Service Providers?

A: It’s a design principle where high-level modules should not depend on low-level modules, but both should depend on abstractions. In Laravel, you bind an Interface to a Concrete Implementation in a Service Provider.

Q42: How does Laravel’s “Task Scheduling” work?

A: Instead of creating multiple Cron entries on your server, you define a single Cron entry that calls php artisan schedule:run. You then define your schedule inside app/Console/Kernel.php.

Q43: What is “Polymorphic Relationship”?

A: A polymorphic relationship allows a model to belong to more than one other model on a single association. For example, a Comment model might belong to both Post and Video models.

Q44: What are “Global Scopes” in Eloquent?

A: Global scopes allow you to add constraints to all queries for a given model. For example, a User model could have a global scope that only ever retrieves “active” users.

Q45: Explain the “Repository Pattern” in Laravel.

A: It is a design pattern that abstracts data access logic. It sits between the Controller and the Model, making the code more testable and decoupling the application from the database technology.

Q46: What is “Laravel Echo”?

A: Laravel Echo is a JavaScript library that makes it easy to subscribe to channels and listen for events broadcast by your Laravel application.

Q47: How do you optimize Laravel performance for production?

A:

  • php artisan config:cache
  • php artisan route:cache
  • php artisan view:cache
  • Use Eager Loading to avoid N+1 queries.
  • Use a fast cache driver like Redis.

Q48: What is the “N+1 Query Problem”?

A: It occurs when you load a collection of models and then loop through them to load a related model, resulting in one query for the collection and $N$ additional queries for the relations. It is solved using with().

Q49: How do you implement “Authorization” in Laravel?

A: Laravel provides Gates (closure-based) and Policies (class-based). Policies are typically organized around a specific model to authorize actions like view or update.

Q50: What is “Contract” in Laravel?

A: Laravel Contracts are a set of interfaces that define the core services provided by the framework. For example, Illuminate\Contracts\Queue\Queue defines the methods needed for queuing. They serve as documented abstractions.