Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Sunday, September 7, 2025

The Ultimate Laravel Interview Guide: 100+ Questions for Beginners to Experts

 

The Ultimate Laravel Interview Guide: 100+ Questions for Beginners to Experts

Preparing for a Laravel developer role? This comprehensive guide is your secret weapon. We've compiled over 100 of the most competitive Laravel interview questions, categorized by role and complexity—from foundational knowledge for beginners to deep architectural puzzles for experts. Each question is designed to test not just memorization, but real-world understanding, problem-solving skills, and coding prowess.

Let's dive in!

Table of Contents

  1. Beginner Level (0-2 years experience)

  2. Intermediate Level (2-5 years experience)

  3. Expert Level (5+ years experience)


Beginner Level Questions <a name="beginner"></a>

Focus: Basic understanding, core concepts, and simple implementations.

Core & MVC Architecture

  1. What is Laravel, and what are its main advantages over other PHP frameworks?
    (Tests basic market awareness)

  2. Explain the MVC architecture. How does Laravel implement it?

    • Model: Represents the data and business logic (e.g., an App\Models\User class).

    • View: Presents the data to the user (Blade templates).

    • Controller: Handles user requests, interacts with the Model, and returns a View/Response.

  3. What is the purpose of the artisan command-line tool? Give three examples of common artisan commands.

    • Example: php artisan make:model Product -mcr (creates a Model, Migration, and Controller).

  4. What are Service Providers? Name one core service provider that Laravel uses by default.
    (Looks for knowledge of bootstrapping. Answer: RouteServiceProviderAppServiceProvider)

Routing & Basic Controllers

  1. How do you define a basic GET route that returns a view?

    php
    // routes/web.php
    Route::get('/welcome', function () {
        return view('welcome');
    });
  2. What is the difference between Route::get() and Route::post()?
    (Tests understanding of HTTP verbs)

  3. How do you pass a URL parameter (e.g., an id) to a route and access it in a controller?

    php
    Route::get('/user/{id}', [UserController::class, 'show']);
    // In UserController
    public function show($id) { ... }

Blade Templating

  1. How do you display a PHP variable $name in a Blade template?
    {{ $name }}

  2. What is the Blade directive for including a sub-view?
    @include('partials.header')

  3. How do you create a loop in Blade to display an array of $products?

    blade
    @foreach($products as $product)
        <p>{{ $product->name }}</p>
    @endforeach

Basics of Eloquent ORM

  1. What is Eloquent? What is an Eloquent Model?
    (Object-Relational Mapper that allows interacting with databases using an object-oriented syntax)

  2. How do you retrieve all records from a posts table using Eloquent? Assume the model is Post.
    $posts = Post::all();

  3. How do you retrieve a single record by its primary key?
    $post = Post::find(1);

  4. What is the naming convention for Eloquent model names and database table names?

    • Model: Post (Singular, PascalCase)

    • Table: posts (Plural, snake_case)

Migrations & Databases

  1. What are migrations? What problem do they solve?
    (Version control for your database schema.)

  2. How do you create a new migration file to create a products table?
    php artisan make:migration create_products_table

  3. Write a migration to add a title (string) and description (text) column to a table.

    php
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }
  4. How do you run all pending migrations?
    php artisan migrate

Basic Validation

  1. How would you validate that a email field is required and formatted correctly in a Laravel controller?

    php
    $validated = $request->validate([
        'email' => 'required|email',
    ]);

Security Basics

  1. What is CSRF protection, and how does Laravel enable it by default for web forms?

    • Answer: Laravel automatically generates a CSRF token for each active user session. You must include @csrf in your forms.


Intermediate Level Questions <a name="intermediate"></a>

Focus: Deeper understanding of components, real-world scenarios, and application architecture.

Advanced Eloquent & Relationships

  1. Explain the different types of Eloquent relationships.
    (HasOne, HasMany, BelongsTo, BelongsToMany, ManyToMany)

  2. Scenario: A User hasMany Posts. How would you define this relationship in the User model? How would you eager load a user's posts to avoid the N+1 query problem?

    php
    // In User.php model
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
    // Eager Loading
    $users = User::with('posts')->get();
  3. What are Eloquent Accessors and Mutators? Write an example of a accessor for a first_name field that always capitalizes the first letter.

    php
    public function getFirstNameAttribute($value)
    {
        return ucfirst($value);
    }
  4. What is query scoping? Create a local scope to get only active products.

    php
    // In Product.php model
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
    // Usage: Product::active()->get();
  5. What is the difference between $fillable and $guarded properties in an Eloquent model?

    • $fillable: Whitelist of attributes that are mass assignable.

    • $guarded: Blacklist of attributes that are not mass assignable.

Advanced Routing & Middleware

  1. What is Middleware? Give two examples of built-in Laravel middleware.
    (Answer: auththrottlewebapi)

  2. How do you create a custom middleware to check if a user is an admin? What are the steps?

    • Create: php artisan make:middleware IsAdmin

    • Implement logic in handle method.

    • Register it in app/Http/Kernel.php.

    • Attach it to a route.

  3. What are Route Groups? How would you apply the auth middleware to a group of routes and prefix them with /admin?

    php
    Route::prefix('admin')->middleware('auth')->group(function () {
        Route::get('/dashboard', 'AdminController@dashboard');
    });
  4. What is Route Model Binding? Show implicit and explicit binding.

    • Implicit: Route::get('/user/{user}', ...); -> public function show(User $user)

    • Explicit: Defining custom logic in RouteServiceProvider::boot().

Service Container & Dependency Injection

  1. What is the Laravel Service Container?
    (A powerful tool for managing class dependencies and performing dependency injection.)

  2. What is Dependency Injection? Show an example of Constructor Injection in a Laravel controller.

    php
    public function __construct(UserRepository $users)
    {
        $this->users = $users;
    }
  3. What are Facades? How do they work under the hood?
    (Facades provide a "static" interface to classes registered in the service container. They proxy calls to the underlying object via the __callStatic() magic method.)

Forms & Requests

  1. What are Form Requests and why are they useful?
    (Custom request classes that handle authorization and validation logic, keeping controllers clean.)

  2. How do you handle file uploads in Laravel? Store an uploaded avatar image in the storage/app/public directory and make sure it's accessible from the web.

    php
    $path = $request->file('avatar')->store('avatars', 'public');
    // Don't forget to run `php artisan storage:link`

API Development (Laravel Sanctum/Passport)

  1. How would you create a simple API endpoint that returns a list of products as JSON?

    php
    Route::get('/api/products', function () {
        return response()->json(Product::all());
    });
  2. What is the difference between Laravel Sanctum and Laravel Passport? When would you use one over the other?

    • Sanctum: Lightweight, for SPAs, mobile apps, and simple token-based APIs.

    • Passport: Full OAuth2 server implementation, for complex API ecosystems.

Testing

  1. What are the two main types of tests in Laravel?
    (Unit tests and Feature tests.)

  2. Write a basic feature test to ensure the /home route returns a 200 status code for an authenticated user.

    php
    public function test_home_route_for_authenticated_user()
    {
        $user = User::factory()->create();
        $this->actingAs($user)
             ->get('/home')
             ->assertStatus(200);
    }

Performance & Debugging

  1. What is the N+1 query problem? How do you identify and fix it in Laravel?

    • Identify: Use Laravel Debugbar or DB::listen.

    • Fix: Use eager loading (with()).

  2. What is Laravel Caching? How would you cache the result of an expensive database query for 24 hours?

    php
    $products = Cache::remember('all-products', 60 * 24, function () {
        return Product::all();
    });

Expert Level Questions <a name="expert"></a>

Focus: System design, deep internals, performance optimization, and security hardening.

Advanced Architecture & Patterns

  1. Explain the Repository Pattern. What are its benefits, and how would you implement it in Laravel?
    (Abstracts data access logic, making code more testable and flexible. Bind a concrete repository to an interface via the Service Container.)

  2. What is the Service Layer pattern? Should business logic go in controllers or models?
    (Expert opinion: Controllers handle HTTP, Models handle data, a Service Layer handles complex business rules. This keeps classes slim and focused.)

  3. When would you use Laravel Queues? Describe a scenario and how you'd implement it.

    • Scenario: Sending welcome emails to 10,000 new users.

    • Implementation: Dispatch a SendWelcomeEmail job to a queue.

  4. How do Laravel Queues work under the hood? Explain the relationship between jobs, workers, and the queue database/Redis.
    (Jobs are pushed to a queue driver (e.g., Redis). Workers run continuously, listening to the queue and processing jobs.)

  5. What are Laravel Events and Listeners? How do they facilitate a decoupled application design?
    (An event is fired when something significant happens. Listeners react to that event without the firing code needing to know about them.)

Deep Dive into the Container

  1. Explain the difference between bind()singleton(), and instance() methods in the Service Container.

    • bind(): A new instance is resolved every time.

    • singleton(): The same instance is shared and returned every time.

    • instance(): Bind an existing object instance.

  2. How does Service Provider deferred loading work?
    (A provider can be deferred if it only registers bindings and doesn't need to execute on every request, improving performance.)

Advanced Security

  1. How can you prevent SQL injection in Laravel? Is Eloquent enough?
    (Yes, Eloquent and the Query Builder use PDO parameter binding, making them inherently secure against SQL injection. The risk comes from using raw queries unsafely.)

  2. Explain XSS and how Laravel helps protect against it. When are you still vulnerable?

    • Protection: The {{ }} Blade syntax automatically escapes output.

    • Vulnerability: When using {!! !!} on user-provided data without sanitization.

  3. What is Mass Assignment and how does Laravel protect against it? Can you give an example of a vulnerable mass assignment implementation?

    • Protection: The $fillable or $guarded properties on the model.

    • Vulnerable Example:

      php
      // In Controller
      Post::create($request->all());
      // If the model has no $fillable/$guarded, a user could pass `is_admin => true`.

Performance & Scaling

  1. How would you optimize a Laravel application for high traffic? List strategies from database to application to server level.

    • Database: Indexing, query optimization, read/write replicas.

    • Application: Caching (Redis/Memcached), Queues, OPCache, Composer Optimize.

    • Server: CDN, Load Balancers, Horizontal Scaling.

  2. What is Laravel Octane? How does it fundamentally change the request lifecycle, and what are the trade-offs?
    (Uses Swoole/RoadRunner to keep the application bootstrapped in memory between requests, dramatically increasing performance. Trade-off: requires careful management of static/global state.)

Advanced Eloquent & Database

  1. How would you update a table with millions of records without locking it or causing downtime?
    (Use chunking and avoid get()User::chunk(1000, function ($users) { ... }); or use cursors.)

  2. What are Polymorphic Relationships? Describe a real-world scenario and implement it.

    • Scenario: Comments can belong to a Post or a Video.

    • Implementation:

      php
      // comments table: id, body, commentable_id, commentable_type
      class Comment extends Model {
          public function commentable() {
              return $this->morphTo();
          }
      }
      class Post extends Model {
          public function comments() {
              return $this->morphMany(Comment::class, 'commentable');
          }
      }

API & Microservices

  1. How would you design a rate-limiting strategy for a public API in Laravel?
    (Use Laravel's built-in throttle:60,1 middleware for simple cases. For more complex needs (per-user, per-endpoint), implement a custom solution using the Cache.)

  2. How can you implement API versioning in Laravel?
    (Common strategies: URL prefix (/api/v1/posts), HTTP headers (Accept: application/json; version=1.0).)

  3. What are the challenges of moving from a monolith to a microservices architecture with Laravel? How would you share authentication between services?
    (Challenges: Data consistency, network latency, debugging. Authentication: Use a shared OAuth2 server (Passport) or JWT tokens.)

Expert Level Questions (Continued) <a name="expert"></a>

Testing & TDD

  1. What is the difference between Unit Tests, Feature Tests, and Integration Tests in the context of Laravel?

    • Unit: Tests a single class or method in isolation (often with mocks).

    • Feature: Tests a larger portion of code, like a full API endpoint or user interaction, interacting with the framework.

    • Integration: Tests the interaction between multiple components (e.g., a service and a repository).

  2. How would you test a queued job without actually pushing it to a queue?
    Use Laravel's Queue::fake() and then assert the job was pushed.

    php
    public function test_job_is_pushed()
    {
        Queue::fake();
        // Execute the code that dispatches the job
        ProcessPodcast::dispatch($podcast);
        // Assert a job was pushed...
        Queue::assertPushed(ProcessPodcast::class);
    }
  3. How do you mock an external API call within a Laravel test?
    Use Laravel's Http facade to fake responses.

    php
    Http::fake([
        'weather-api.com/*' => Http::response(['temp' => 72], 200),
    ]);
    // Your code that calls the API will now get this fake response.

Deployment & DevOps

  1. What is the purpose of the php artisan optimize command in a deployment process? Is it still necessary in recent Laravel versions?
    *(It caches the bootstrap files. As of Laravel 5.8+, it's largely unnecessary for performance in production if you're using OPcache, but config:cache and route:cache are still critical.)*

  2. How does Laravel Forge or Envoyer simplify deployment? What underlying principles do they use?
    (They automate zero-downtime deployments, often using symbolic links for the current release and managing queues and Horizon during deployment.)

  3. Explain a zero-downtime deployment strategy for a Laravel application.

    1. Build the new version of the app in a new directory (releases/v2).

    2. Run composer installnpm buildphp artisan config:cache.

    3. Symlink shared storage (storage.env) to the new release.

    4. Atomically switch the current public symlink to point to the new release.

    5. Run database migrations after the symlink switch (to avoid downtime if they fail).

    6. Reload PHP-FPM.

Advanced Problems & Scenarios

  1. Scenario: Your Laravel application is suddenly very slow. Describe your step-by-step debugging process.

    • Step 1: Check Laravel Debugbar or Telescope for slow queries, N+1 problems.

    • Step 2: Check server metrics (CPU, RAM, I/O) – htopiotop.

    • Step 3: Check slow query logs in the database.

    • Step 4: Check application logs (storage/logs/laravel.log) for errors.

    • Step 5: Check cache and queue driver connectivity (Redis, Beanstalkd).

  2. How would you implement a real-time notification feature (like a live news ticker) in Laravel? Compare different approaches.

    • Polling: Simple (setInterval in JS to hit an API) but inefficient.

    • Laravel Echo Server + WebSockets: Modern, efficient, real-time. Uses Pusher or a Laravel WebSocket server.

    • Server-Sent Events (SSE): Simpler than WebSockets, one-way communication from server to client.

  3. You need to process a large CSV file (1GB+) and import its rows into the database. How would you architect this in Laravel to avoid memory limits?

    • Use Laravel's job batches.

    • Read the file in chunks using generators (fgetcsv in a loop).

    • Dispatch a job for each chunk of rows (e.g., 1000 rows per job).

    • Use a queue worker (e.g., Horizon) to process the jobs.

  4. How do you handle database transactions in Laravel? Write an example where you create a new user and their first post in a single transaction.

    php
    DB::transaction(function () use ($request) {
        $user = User::create($request->only('name', 'email'));
        // If this fails, the user creation is rolled back
        $user->posts()->create($request->only('title', 'content'));
    });
  5. What are Value Objects? How would you implement one in Laravel, perhaps for a Money value (amount and currency)?
    (A value object is an immutable object whose equality is based on its property values, not its identity. Implementation often involves Casts.)

    php
    // In the Model
    protected $casts = [
        'price' => MoneyCast::class,
    ];
    // MoneyCast class would serialize/deserialize to a Money object.
  6. Explain the CQRS (Command Query Responsibility Segregation) pattern. How could its principles be applied in a Laravel project?

    • Principle: Separate the model that reads data (Queries) from the model that writes data (Commands).

    • Laravel Application: Use simple Eloquent models for reads. Use dedicated Action or Service classes (e.g., CreateOrderAction) for writes, which encapsulate all the business logic.

  7. How would you implement a multi-tenant SaaS application in Laravel (where each customer has isolated data)?

    • Approach 1: Separate databases per tenant. Use a central DB to track tenants and their database connections. Dynamically switch connections.

    • Approach 2: Single database, with a tenant_id on all tenant-specific tables. Use a global scope to automatically scope all queries by the current tenant_id.

    • Package: Often implemented using packages like stancl/tenancy.


Final Set of Questions (Mix of Complexities) <a name="final"></a>

  1. What is the scheduling feature in Laravel? How does it work on a server?
    (The App\Console\Kernel::schedule method defines commands to run. On the server, a single cron entry * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1 runs every minute and Laravel evaluates if any tasks are due.)

  2. What are Macros? How would you add a custom method to the Eloquent Builder?
    php use Illuminate\Database\Eloquent\Builder; Builder::macro('active', function () { return $this->where('is_active', 1); }); // Usage: User::active()->get();

  3. What is the purpose of the App\Exceptions\Handler class?
    (The central place to handle how your application responds to exceptions: reporting them and rendering HTTP responses.)

  4. How can you customize the pagination views generated by Laravel?
    php artisan vendor:publish --tag=laravel-pagination

  5. What are the benefits of using API Resources?
    (Transform and format Eloquent models and collections into JSON API responses, acting as a transformation layer.)

  6. What is the difference between softDeletes() and forceDelete()?
    softDeletes(): Sets deleted_at timestamp. Model is not included in future queries.
    forceDelete(): Permanently removes the record from the database.

  7. How do you create a custom validation rule?
    php artisan make:rule Uppercase
    Implement the passes and message methods.

  8. What is the has() method used for in Eloquent?
    (To query based on the existence of a relationship. User::has('posts')->get() gets all users who have at least one post.)

  9. How would you implement a "remember me" functionality during authentication?
    (The Laravel auth middleware handles this out-of-the-box. It involves a long-lived cookie and a token stored in the users table.)

  10. What is the purpose of the $casts property in an Eloquent model?
    (To define attributes that should be converted to common data types, like arrayjsondatetime, or boolean.)

  11. How do you handle localization (i18n) in Laravel?
    (Use the __() helper function. Translation strings are stored in files in the resources/lang directory.)

  12. What is the replicate() method used for in Eloquent?
    (To create a new, unsaved instance of a model with all its attributes copied. Useful for creating "duplicate" records.)

  13. How can you monitor your Laravel application in production?
    (Tools: Laravel Telescope, Laravel Horizon, monitoring services (Sentry, Bugsnag), APM tools (DataDog, New Relic).)

  14. What is the tap() helper function used for?
    (It allows you to "tap" into a fluent chain, perform an action on the passed value, and then return the value. Useful for debugging or adding side effects within a chain.)

  15. How would you implement a search feature across multiple model attributes?
    (Use a package like Laravel Scout with a driver like Algolia or Meilisearch for advanced full-text search. For simpler needs, use where() clauses with orWhere().)

  16. What is method injection in a controller? How is it different from constructor injection?
    (You can type-hint dependencies in a controller's method in addition to the constructor. The container will inject them. Useful for dependencies only needed in a single method.)
    php public function store(Request $request, ImageProcessor $processor) { ... }

  17. Explain the concept of "contracts" in Laravel. What is the Illuminate\Contracts namespace?
    (Contracts are interfaces that define the core services provided by the framework (e.g., CacheQueueMailer). Using interfaces makes code more flexible and testable.)

  18. How does Laravel's authentication system work behind the scenes?
    (It uses guards (e.g., webapi) and providers (e.g., eloquent). The session guard maintains state using cookies, while the token guard authenticates via an API token.)

  19. What is the purpose of the php artisan down and up commands?
    (To put your application into maintenance mode and bring it back online.)

  20. How can you extend a Blade component?
    (Use component slots and the x-slots syntax to create flexible layouts.)

  21. What is the resolve() helper function used for?
    (To resolve a class instance out of the service container.)
    $api = resolve('MyApiService');

  22. How would you handle a situation where you need to change the structure of a cached config file during deployment?
    (Always run php artisan config:cache at the end of your deployment process to recache the new configuration.)

  23. What is the optional() helper function used for?
    (To avoid null pointer errors. It allows you to call methods or access properties on an object that might be null. If the object is null, the call will return null instead of causing an error.)
    return optional($user->address)->country;

  24. Describe how you would implement a feature that requires long-running PHP processes (like a WebSocket server).
    (Use a process manager like Supervisor to run and monitor Laravel Echo Server or a custom Artisan command as a daemon.)

  25. What is the difference between where() and whereIn()?
    where('column', 'value'): Checks if a column equals a single value.
    whereIn('column', [1, 2, 3]): Checks if a column's value is present in a given array of values.

  26. How can you share a variable with all your Blade templates?
    (Use a View Composer, often registered in a service provider's boot() method.)
    php View::composer('*', function ($view) { $view->with('categories', Category::all()); });

  27. What is the Gate::before() method used for?
    (To define a callback that is run before all other authorization checks. If it returns a non-null result, that result will be considered the result of the check. Useful for granting full access to admins.)

  28. How would you create a console command that asks the user for input?
    (Use the ask()confirm(), and choice() methods within the command's handle() method.)

  29. What is the Collection class? Why is it powerful?
    (A wrapper around arrays providing a fluent, convenient interface for mapping, reducing, filtering, and transforming data.)

  30. How do you handle circular dependencies within the Service Container?
    (This is often a sign of bad design. Refactor the code to remove the circular dependency. If absolutely necessary, use a setter injection instead of a constructor injection to break the cycle.)

  31. Explain the Lazy Collections feature. When would you use it?
    (Lazy Collections leverage PHP generators to handle massive datasets with very low memory usage. You'd use it when processing huge files or large database results.)
    $users = User::cursor()->filter(...); // Returns a LazyCollection

  32. How would you implement a custom Filesystem Disk (e.g., to store files on FTP or SFTP)?
    (Define the disk's driver and configuration in config/filesystems.php. Laravel's Flysystem integration makes this possible.)

  33. What is the purpose of the $hidden property on an Eloquent model?
    (To specify which attributes should be hidden when the model is converted to an array or JSON (e.g., passwordapi_token).)

  34. Describe a scenario where you would use a Pivot model in a Many-to-Many relationship.
    (When the intermediate (pivot) table has additional attributes beyond the foreign keys. For example, a role_user pivot table might have a assigned_by and assigned_at column.)

  35. How does Laravel's encryption work? What is required to decrypt data?
    *(It uses OpenSSL for AES-256-CBC encryption. The APP_KEY in the .env file is essential. Data encrypted with one APP_KEY cannot be decrypted with another.)*

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam

Post Bottom Ad

Responsive Ads Here