InterviewTreedInterviewTreed

InterviewTreed Question Bank

PHP & Laravel Interview Questions and Answers

Prepare for PHP programming, object-oriented development, Laravel framework, REST APIs, database integration, authentication, and modern PHP application development.

Total Questions

125

Beginner

44

Intermediate

71

Advanced

10

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1PHP fundamentals

What is PHP and where does it run?

Interview answer for what is php and where does it run? with syntax and a practical Laravel/PHP pattern.

Answer

What is PHP and where does it run? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q2PHP fundamentals

What are PHP variables and types?

Interview answer for what are php variables and types? with syntax and a practical Laravel/PHP pattern.

Answer

What are PHP variables and types? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q3PHP fundamentals

What is the difference between == and === in PHP?

Interview answer for what is the difference between == and === in php? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between == and === in PHP? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q4PHP fundamentals

How do arrays work in PHP?

Interview answer for how do arrays work in php? with syntax and a practical Laravel/PHP pattern.

Answer

How do arrays work in PHP? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q5PHP fundamentals

What are associative arrays?

Interview answer for what are associative arrays? with syntax and a practical Laravel/PHP pattern.

Answer

What are associative arrays? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q6PHP fundamentals

How do you handle null values in PHP?

Interview answer for how do you handle null values in php? with syntax and a practical Laravel/PHP pattern.

Answer

How do you handle null values in PHP? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q9PHP fundamentals

What are exceptions in PHP?

Interview answer for what are exceptions in php? with syntax and a practical Laravel/PHP pattern.

Answer

What are exceptions in PHP? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q11PHP fundamentals

What is Composer?

Interview answer for what is composer? with syntax and a practical Laravel/PHP pattern.

Answer

What is Composer? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q14Object-oriented PHP and modern language features

Explain encapsulation, inheritance, and polymorphism in PHP

Interview answer for explain encapsulation, inheritance, and polymorphism in php with syntax and a practical Laravel/PHP pattern.

Answer

Explain encapsulation, inheritance, and polymorphism in PHP is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q15Object-oriented PHP and modern language features

What are constructors and destructors?

Interview answer for what are constructors and destructors? with syntax and a practical Laravel/PHP pattern.

Answer

What are constructors and destructors? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q18Object-oriented PHP and modern language features

What are arrow functions?

Interview answer for what are arrow functions? with syntax and a practical Laravel/PHP pattern.

Answer

What are arrow functions? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q27Laravel architecture and configuration

What is Laravel and what problems does it solve?

Interview answer for what is laravel and what problems does it solve? with syntax and a practical Laravel/PHP pattern.

Answer

What is Laravel and what problems does it solve? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q32Laravel architecture and configuration

What is the difference between config and .env?

Interview answer for what is the difference between config and .env? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between config and .env? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q33Laravel architecture and configuration

What are Artisan commands?

Interview answer for what are artisan commands? with syntax and a practical Laravel/PHP pattern.

Answer

What are Artisan commands? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q34Laravel architecture and configuration

What is the Laravel directory structure?

Interview answer for what is the laravel directory structure? with syntax and a practical Laravel/PHP pattern.

Answer

What is the Laravel directory structure? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q40Routing and controllers

How do you define routes in Laravel?

Interview answer for how do you define routes in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

How do you define routes in Laravel? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q41Routing and controllers

What is the difference between web.php and api.php?

Interview answer for what is the difference between web.php and api.php? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between web.php and api.php? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q42Routing and controllers

How do route parameters work?

Interview answer for how do route parameters work? with syntax and a practical Laravel/PHP pattern.

Answer

How do route parameters work? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q44Routing and controllers

How do named routes work?

Interview answer for how do named routes work? with syntax and a practical Laravel/PHP pattern.

Answer

How do named routes work? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q45Routing and controllers

What are resource controllers?

Interview answer for what are resource controllers? with syntax and a practical Laravel/PHP pattern.

Answer

What are resource controllers? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q49Routing and controllers

How do you inspect registered routes?

Interview answer for how do you inspect registered routes? with syntax and a practical Laravel/PHP pattern.

Answer

How do you inspect registered routes? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q50Routing and controllers

How do you return JSON from a controller?

Interview answer for how do you return json from a controller? with syntax and a practical Laravel/PHP pattern.

Answer

How do you return JSON from a controller? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q53Middleware and request pipeline

What is middleware in Laravel?

Interview answer for what is middleware in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

What is middleware in Laravel? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q54Middleware and request pipeline

How do you create custom middleware?

Interview answer for how do you create custom middleware? with syntax and a practical Laravel/PHP pattern.

Answer

How do you create custom middleware? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q60Middleware and request pipeline

How do you handle maintenance mode?

Interview answer for how do you handle maintenance mode? with syntax and a practical Laravel/PHP pattern.

Answer

How do you handle maintenance mode? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q66Eloquent ORM and relationships

What is Eloquent ORM?

Interview answer for what is eloquent orm? with syntax and a practical Laravel/PHP pattern.

Answer

What is Eloquent ORM? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q67Eloquent ORM and relationships

How do you define an Eloquent model?

Interview answer for how do you define an eloquent model? with syntax and a practical Laravel/PHP pattern.

Answer

How do you define an Eloquent model? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q69Eloquent ORM and relationships

How do you define one-to-one relationships?

Interview answer for how do you define one-to-one relationships? with syntax and a practical Laravel/PHP pattern.

Answer

How do you define one-to-one relationships? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q70Eloquent ORM and relationships

How do you define one-to-many relationships?

Interview answer for how do you define one-to-many relationships? with syntax and a practical Laravel/PHP pattern.

Answer

How do you define one-to-many relationships? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q78Migrations, database, and query performance

What are Laravel migrations?

Interview answer for what are laravel migrations? with syntax and a practical Laravel/PHP pattern.

Answer

What are Laravel migrations? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q79Migrations, database, and query performance

How do you create and roll back a migration?

Interview answer for how do you create and roll back a migration? with syntax and a practical Laravel/PHP pattern.

Answer

How do you create and roll back a migration? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q80Migrations, database, and query performance

What are seeders and factories?

Interview answer for what are seeders and factories? with syntax and a practical Laravel/PHP pattern.

Answer

What are seeders and factories? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q82Migrations, database, and query performance

How do you enforce unique constraints?

Interview answer for how do you enforce unique constraints? with syntax and a practical Laravel/PHP pattern.

Answer

How do you enforce unique constraints? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q87Migrations, database, and query performance

How do you avoid SQL injection in Laravel?

Interview answer for how do you avoid sql injection in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

How do you avoid SQL injection in Laravel? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q90Authentication, authorization, and security

What is Laravel authentication?

Interview answer for what is laravel authentication? with syntax and a practical Laravel/PHP pattern.

Answer

What is Laravel authentication? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q94Authentication, authorization, and security

How do you protect routes with auth middleware?

Interview answer for how do you protect routes with auth middleware? with syntax and a practical Laravel/PHP pattern.

Answer

How do you protect routes with auth middleware? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q97Authentication, authorization, and security

How does password hashing work in Laravel?

Interview answer for how does password hashing work in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

How does password hashing work in Laravel? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q100Authentication, authorization, and security

How do you validate and sanitize user input?

Interview answer for how do you validate and sanitize user input? with syntax and a practical Laravel/PHP pattern.

Answer

How do you validate and sanitize user input? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q102API development and validation

How do you build a REST API in Laravel?

Interview answer for how do you build a rest api in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

How do you build a REST API in Laravel? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q110API development and validation

How do you test API endpoints?

Interview answer for how do you test api endpoints? with syntax and a practical Laravel/PHP pattern.

Answer

How do you test API endpoints? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q114Testing, queues, caching, and deployment

How do you write feature tests in Laravel?

Interview answer for how do you write feature tests in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

How do you write feature tests in Laravel? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q115Testing, queues, caching, and deployment

What is the difference between unit and feature tests?

Interview answer for what is the difference between unit and feature tests? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between unit and feature tests? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q118Testing, queues, caching, and deployment

How do you use Laravel cache?

Interview answer for how do you use laravel cache? with syntax and a practical Laravel/PHP pattern.

Answer

How do you use Laravel cache? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q124Testing, queues, caching, and deployment

How do you schedule recurring tasks?

Interview answer for how do you schedule recurring tasks? with syntax and a practical Laravel/PHP pattern.

Answer

How do you schedule recurring tasks? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q7PHP fundamentals

What are type declarations and return types?

Interview answer for what are type declarations and return types? with syntax and a practical Laravel/PHP pattern.

Answer

What are type declarations and return types? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q8PHP fundamentals

What are union and nullable types?

Interview answer for what are union and nullable types? with syntax and a practical Laravel/PHP pattern.

Answer

What are union and nullable types? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q10PHP fundamentals

How do namespaces and use statements work?

Interview answer for how do namespaces and use statements work? with syntax and a practical Laravel/PHP pattern.

Answer

How do namespaces and use statements work? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q12PHP fundamentals

How does PSR-4 autoloading work?

Interview answer for how does psr-4 autoloading work? with syntax and a practical Laravel/PHP pattern.

Answer

How does PSR-4 autoloading work? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q13PHP fundamentals

What are traits in PHP?

Interview answer for what are traits in php? with syntax and a practical Laravel/PHP pattern.

Answer

What are traits in PHP? is a key concept in php fundamentals. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q16Object-oriented PHP and modern language features

What are static properties and methods?

Interview answer for what are static properties and methods? with syntax and a practical Laravel/PHP pattern.

Answer

What are static properties and methods? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q17Object-oriented PHP and modern language features

What are anonymous functions and closures?

Interview answer for what are anonymous functions and closures? with syntax and a practical Laravel/PHP pattern.

Answer

What are anonymous functions and closures? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q19Object-oriented PHP and modern language features

What are generators and yield?

Interview answer for what are generators and yield? with syntax and a practical Laravel/PHP pattern.

Answer

What are generators and yield? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q20Object-oriented PHP and modern language features

What are enums in PHP?

Interview answer for what are enums in php? with syntax and a practical Laravel/PHP pattern.

Answer

What are enums in PHP? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q22Object-oriented PHP and modern language features

What is dependency injection?

Interview answer for what is dependency injection? with syntax and a practical Laravel/PHP pattern.

Answer

What is dependency injection? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q24Object-oriented PHP and modern language features

What is the difference between composition and inheritance?

Interview answer for what is the difference between composition and inheritance? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between composition and inheritance? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q25Object-oriented PHP and modern language features

How do you write unit tests for PHP code?

Interview answer for how do you write unit tests for php code? with syntax and a practical Laravel/PHP pattern.

Answer

How do you write unit tests for PHP code? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q26Object-oriented PHP and modern language features

How should secrets and environment variables be managed?

Interview answer for how should secrets and environment variables be managed? with syntax and a practical Laravel/PHP pattern.

Answer

How should secrets and environment variables be managed? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q28Laravel architecture and configuration

Explain Laravel's request lifecycle

Interview answer for explain laravel's request lifecycle with syntax and a practical Laravel/PHP pattern.

Answer

Explain Laravel's request lifecycle is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q29Laravel architecture and configuration

What is the service container?

Interview answer for what is the service container? with syntax and a practical Laravel/PHP pattern.

Answer

What is the service container? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q30Laravel architecture and configuration

What is a service provider?

Interview answer for what is a service provider? with syntax and a practical Laravel/PHP pattern.

Answer

What is a service provider? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q31Laravel architecture and configuration

What are facades in Laravel?

Interview answer for what are facades in laravel? with syntax and a practical Laravel/PHP pattern.

Answer

What are facades in Laravel? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q35Laravel architecture and configuration

What is route caching?

Interview answer for what is route caching? with syntax and a practical Laravel/PHP pattern.

Answer

What is route caching? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q36Laravel architecture and configuration

How do you create a custom Artisan command?

Interview answer for how do you create a custom artisan command? with syntax and a practical Laravel/PHP pattern.

Answer

How do you create a custom Artisan command? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q38Laravel architecture and configuration

How do Laravel events and listeners work?

Interview answer for how do laravel events and listeners work? with syntax and a practical Laravel/PHP pattern.

Answer

How do Laravel events and listeners work? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q39Laravel architecture and configuration

What are queues and jobs?

Interview answer for what are queues and jobs? with syntax and a practical Laravel/PHP pattern.

Answer

What are queues and jobs? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q43Routing and controllers

What is route model binding?

Interview answer for what is route model binding? with syntax and a practical Laravel/PHP pattern.

Answer

What is route model binding? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q46Routing and controllers

What is an invokable controller?

Interview answer for what is an invokable controller? with syntax and a practical Laravel/PHP pattern.

Answer

What is an invokable controller? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q47Routing and controllers

How do you group routes with prefixes and names?

Interview answer for how do you group routes with prefixes and names? with syntax and a practical Laravel/PHP pattern.

Answer

How do you group routes with prefixes and names? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q48Routing and controllers

How do you constrain route parameters?

Interview answer for how do you constrain route parameters? with syntax and a practical Laravel/PHP pattern.

Answer

How do you constrain route parameters? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q51Routing and controllers

What is implicit vs explicit route model binding?

Interview answer for what is implicit vs explicit route model binding? with syntax and a practical Laravel/PHP pattern.

Answer

What is implicit vs explicit route model binding? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q52Routing and controllers

How do you handle 404 and 500 errors?

Interview answer for how do you handle 404 and 500 errors? with syntax and a practical Laravel/PHP pattern.

Answer

How do you handle 404 and 500 errors? is a key concept in routing and controllers. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q55Middleware and request pipeline

How do you register and apply middleware?

Interview answer for how do you register and apply middleware? with syntax and a practical Laravel/PHP pattern.

Answer

How do you register and apply middleware? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q56Middleware and request pipeline

What is the difference between global and route middleware?

Interview answer for what is the difference between global and route middleware? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between global and route middleware? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q58Middleware and request pipeline

How do you create middleware for role checks?

Interview answer for how do you create middleware for role checks? with syntax and a practical Laravel/PHP pattern.

Answer

How do you create middleware for role checks? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q59Middleware and request pipeline

How do you add headers using middleware?

Interview answer for how do you add headers using middleware? with syntax and a practical Laravel/PHP pattern.

Answer

How do you add headers using middleware? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q61Middleware and request pipeline

How do you throttle requests with middleware?

Interview answer for how do you throttle requests with middleware? with syntax and a practical Laravel/PHP pattern.

Answer

How do you throttle requests with middleware? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q62Middleware and request pipeline

How do you skip middleware for selected routes?

Interview answer for how do you skip middleware for selected routes? with syntax and a practical Laravel/PHP pattern.

Answer

How do you skip middleware for selected routes? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::get('/items/{item}', [ItemController::class, 'show'])->name('items.show');

Example

Declare a route, pass a validated route parameter to a controller, and return a response with the correct status.

Code example

use App\Http\Controllers\ItemController;
use Illuminate\Support\Facades\Route;

Route::get('/items/{item}', [ItemController::class, 'show'])
    ->whereNumber('item')
    ->name('items.show');

Diagram

HTTP request → Router matches method/path → Middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q64Middleware and request pipeline

How do you test middleware behavior?

Interview answer for how do you test middleware behavior? with syntax and a practical Laravel/PHP pattern.

Answer

How do you test middleware behavior? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q65Middleware and request pipeline

What is CSRF middleware and where is it used?

Interview answer for what is csrf middleware and where is it used? with syntax and a practical Laravel/PHP pattern.

Answer

What is CSRF middleware and where is it used? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q68Eloquent ORM and relationships

What are mass assignment and fillable/guarded?

Interview answer for what are mass assignment and fillable/guarded? with syntax and a practical Laravel/PHP pattern.

Answer

What are mass assignment and fillable/guarded? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q71Eloquent ORM and relationships

How do you define many-to-many relationships?

Interview answer for how do you define many-to-many relationships? with syntax and a practical Laravel/PHP pattern.

Answer

How do you define many-to-many relationships? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q73Eloquent ORM and relationships

What is eager loading?

Interview answer for what is eager loading? with syntax and a practical Laravel/PHP pattern.

Answer

What is eager loading? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q74Eloquent ORM and relationships

How do you prevent the N+1 query problem?

Interview answer for how do you prevent the n+1 query problem? with syntax and a practical Laravel/PHP pattern.

Answer

How do you prevent the N+1 query problem? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q75Eloquent ORM and relationships

What are accessors and mutators?

Interview answer for what are accessors and mutators? with syntax and a practical Laravel/PHP pattern.

Answer

What are accessors and mutators? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q76Eloquent ORM and relationships

What are model casts?

Interview answer for what are model casts? with syntax and a practical Laravel/PHP pattern.

Answer

What are model casts? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q77Eloquent ORM and relationships

What are model events and observers?

Interview answer for what are model events and observers? with syntax and a practical Laravel/PHP pattern.

Answer

What are model events and observers? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q81Migrations, database, and query performance

How do you define indexes in migrations?

Interview answer for how do you define indexes in migrations? with syntax and a practical Laravel/PHP pattern.

Answer

How do you define indexes in migrations? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q83Migrations, database, and query performance

How do you configure multiple database connections?

Interview answer for how do you configure multiple database connections? with syntax and a practical Laravel/PHP pattern.

Answer

How do you configure multiple database connections? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q84Migrations, database, and query performance

How do you use database transactions?

Interview answer for how do you use database transactions? with syntax and a practical Laravel/PHP pattern.

Answer

How do you use database transactions? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q86Migrations, database, and query performance

How do you diagnose slow database queries?

Interview answer for how do you diagnose slow database queries? with syntax and a practical Laravel/PHP pattern.

Answer

How do you diagnose slow database queries? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q88Migrations, database, and query performance

What is cursor pagination and when is it useful?

Interview answer for what is cursor pagination and when is it useful? with syntax and a practical Laravel/PHP pattern.

Answer

What is cursor pagination and when is it useful? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q89Migrations, database, and query performance

How do you perform chunked processing for large tables?

Interview answer for how do you perform chunked processing for large tables? with syntax and a practical Laravel/PHP pattern.

Answer

How do you perform chunked processing for large tables? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q91Authentication, authorization, and security

What is the difference between guards and providers?

Interview answer for what is the difference between guards and providers? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between guards and providers? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q92Authentication, authorization, and security

What are Laravel Sanctum and its common use cases?

Interview answer for what are laravel sanctum and its common use cases? with syntax and a practical Laravel/PHP pattern.

Answer

What are Laravel Sanctum and its common use cases? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q93Authentication, authorization, and security

When would you use Laravel Passport?

Interview answer for when would you use laravel passport? with syntax and a practical Laravel/PHP pattern.

Answer

When would you use Laravel Passport? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q95Authentication, authorization, and security

What are policies and gates?

Interview answer for what are policies and gates? with syntax and a practical Laravel/PHP pattern.

Answer

What are policies and gates? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q96Authentication, authorization, and security

How do you implement role-based authorization?

Interview answer for how do you implement role-based authorization? with syntax and a practical Laravel/PHP pattern.

Answer

How do you implement role-based authorization? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q98Authentication, authorization, and security

How do you implement password reset securely?

Interview answer for how do you implement password reset securely? with syntax and a practical Laravel/PHP pattern.

Answer

How do you implement password reset securely? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q99Authentication, authorization, and security

How do you protect against CSRF?

Interview answer for how do you protect against csrf? with syntax and a practical Laravel/PHP pattern.

Answer

How do you protect against CSRF? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q101Authentication, authorization, and security

How do you prevent mass-assignment vulnerabilities?

Interview answer for how do you prevent mass-assignment vulnerabilities? with syntax and a practical Laravel/PHP pattern.

Answer

How do you prevent mass-assignment vulnerabilities? is a key concept in authentication, authorization, and security. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q103API development and validation

How do you validate requests with Form Requests?

Interview answer for how do you validate requests with form requests? with syntax and a practical Laravel/PHP pattern.

Answer

How do you validate requests with Form Requests? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q104API development and validation

What are API Resources?

Interview answer for what are api resources? with syntax and a practical Laravel/PHP pattern.

Answer

What are API Resources? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q105API development and validation

How do you return consistent API error responses?

Interview answer for how do you return consistent api error responses? with syntax and a practical Laravel/PHP pattern.

Answer

How do you return consistent API error responses? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q106API development and validation

How do you implement filtering, sorting, and pagination?

Interview answer for how do you implement filtering, sorting, and pagination? with syntax and a practical Laravel/PHP pattern.

Answer

How do you implement filtering, sorting, and pagination? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q107API development and validation

How do you version a Laravel API?

Interview answer for how do you version a laravel api? with syntax and a practical Laravel/PHP pattern.

Answer

How do you version a Laravel API? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q108API development and validation

How do you implement API authentication with Sanctum?

Interview answer for how do you implement api authentication with sanctum? with syntax and a practical Laravel/PHP pattern.

Answer

How do you implement API authentication with Sanctum? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q109API development and validation

How do you document APIs with OpenAPI?

Interview answer for how do you document apis with openapi? with syntax and a practical Laravel/PHP pattern.

Answer

How do you document APIs with OpenAPI? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q111API development and validation

How do you handle file uploads through an API?

Interview answer for how do you handle file uploads through an api? with syntax and a practical Laravel/PHP pattern.

Answer

How do you handle file uploads through an API? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q113API development and validation

How do you handle rate limits and 429 responses?

Interview answer for how do you handle rate limits and 429 responses? with syntax and a practical Laravel/PHP pattern.

Answer

How do you handle rate limits and 429 responses? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q116Testing, queues, caching, and deployment

How do you fake events, mail, notifications, and queues in tests?

Interview answer for how do you fake events, mail, notifications, and queues in tests? with syntax and a practical Laravel/PHP pattern.

Answer

How do you fake events, mail, notifications, and queues in tests? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q117Testing, queues, caching, and deployment

How do you test authorization failures?

Interview answer for how do you test authorization failures? with syntax and a practical Laravel/PHP pattern.

Answer

How do you test authorization failures? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware('auth:sanctum')->get('/profile', fn (Request $request) => $request->user());

Example

Authenticate the caller, then separately authorize access to the specific resource; authentication alone is not sufficient.

Code example

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->get('/profile', function (Request $request) {
    return $request->user();
});

Diagram

Request → Authenticate identity → Authorize action/resource → Execute → Safe response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q119Testing, queues, caching, and deployment

What is cache-aside and how can Laravel implement it?

Interview answer for what is cache-aside and how can laravel implement it? with syntax and a practical Laravel/PHP pattern.

Answer

What is cache-aside and how can Laravel implement it? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q121Testing, queues, caching, and deployment

How do queues improve API responsiveness?

Interview answer for how do queues improve api responsiveness? with syntax and a practical Laravel/PHP pattern.

Answer

How do queues improve API responsiveness? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q122Testing, queues, caching, and deployment

How do you retry and handle failed jobs?

Interview answer for how do you retry and handle failed jobs? with syntax and a practical Laravel/PHP pattern.

Answer

How do you retry and handle failed jobs? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q125Testing, queues, caching, and deployment

What should you check before deploying a Laravel application?

Interview answer for what should you check before deploying a laravel application? with syntax and a practical Laravel/PHP pattern.

Answer

What should you check before deploying a Laravel application? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q21Object-oriented PHP and modern language features

What are attributes in PHP?

Interview answer for what are attributes in php? with syntax and a practical Laravel/PHP pattern.

Answer

What are attributes in PHP? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q23Object-oriented PHP and modern language features

What are SOLID principles?

Interview answer for what are solid principles? with syntax and a practical Laravel/PHP pattern.

Answer

What are SOLID principles? is a key concept in object-oriented php and modern language features. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q37Laravel architecture and configuration

What is the difference between singleton and bind in the container?

Interview answer for what is the difference between singleton and bind in the container? with syntax and a practical Laravel/PHP pattern.

Answer

What is the difference between singleton and bind in the container? is a key concept in laravel architecture and configuration. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

<?php
// Define a class, method, or framework configuration that matches the use case.

Example

Use framework conventions and small, testable components; verify behavior with automated tests.

Code example

<?php

declare(strict_types=1);

final class PriceCalculator
{
    public function total(int $unitPriceCents, int $quantity): int
    {
        if ($unitPriceCents < 0 || $quantity < 0) {
            throw new InvalidArgumentException('Values must be non-negative.');
        }

        return $unitPriceCents * $quantity;
    }
}

Diagram

Input → Validation → Application/service logic → Dependency/framework → Output

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q57Middleware and request pipeline

How does middleware order affect a request?

Interview answer for how does middleware order affect a request? with syntax and a practical Laravel/PHP pattern.

Answer

How does middleware order affect a request? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q63Middleware and request pipeline

How do you pass data from middleware to a request?

Interview answer for how do you pass data from middleware to a request? with syntax and a practical Laravel/PHP pattern.

Answer

How do you pass data from middleware to a request? is a key concept in middleware and request pipeline. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::middleware(['auth', 'throttle:60,1'])->group(function () { /* routes */ });

Example

Attach middleware to a route or group so authentication, throttling, or a policy check runs before the controller.

Code example

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequireInternalHeader
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->header('X-Internal-Key') === config('services.internal.key'), 403);
        return $next($request);
    }
}

Diagram

Request → Global middleware → Route middleware → Controller → Response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q72Eloquent ORM and relationships

What are polymorphic relationships?

Interview answer for what are polymorphic relationships? with syntax and a practical Laravel/PHP pattern.

Answer

What are polymorphic relationships? is a key concept in eloquent orm and relationships. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q85Migrations, database, and query performance

How do you lock rows for updates?

Interview answer for how do you lock rows for updates? with syntax and a practical Laravel/PHP pattern.

Answer

How do you lock rows for updates? is a key concept in migrations, database, and query performance. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Schema::table('orders', function (Blueprint $table) { $table->index(['user_id', 'created_at']); });

Example

Add an index that matches common filter/order patterns, then confirm the query plan and write overhead.

Code example

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// Migration example
Schema::table('orders', function (Blueprint $table): void {
    $table->index(['user_id', 'created_at']);
});

// Parameter binding protects values from being interpreted as SQL.
$orders = DB::select(
    'SELECT id, total FROM orders WHERE user_id = ?',
    [$userId]
);

Diagram

Application query → Query builder/ORM → SQL + bindings → Database plan/indexes → Result

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q112API development and validation

How do you implement idempotency for payment-like requests?

Interview answer for how do you implement idempotency for payment-like requests? with syntax and a practical Laravel/PHP pattern.

Answer

How do you implement idempotency for payment-like requests? is a key concept in api development and validation. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Route::post('/api/items', [ItemController::class, 'store'])->middleware('auth:sanctum');

Example

Validate input, authorize the operation, use a resource for response shaping, and return suitable HTTP status codes.

Code example

public function store(StoreItemRequest $request)
{
    $item = Item::create($request->validated());

    return (new ItemResource($item))
        ->response()
        ->setStatusCode(201);
}

Diagram

Client → API route → Auth middleware → Form Request validation → Controller/service → API Resource → JSON

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q120Testing, queues, caching, and deployment

How do you invalidate cache after a model update?

Interview answer for how do you invalidate cache after a model update? with syntax and a practical Laravel/PHP pattern.

Answer

How do you invalidate cache after a model update? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

$posts = Post::with('author')->where('published', true)->latest()->get();

Example

Use Eloquent relationships and eager loading to fetch associated data without issuing a query for each row.

Code example

use App\Models\Post;

$posts = Post::query()
    ->with('author:id,name')
    ->where('published', true)
    ->latest()
    ->get(['id', 'author_id', 'title', 'created_at']);

Diagram

Controller/service → Eloquent model + relationships → SQL queries → Hydrated models → Resource/response

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.
Q123Testing, queues, caching, and deployment

How do you make queued jobs idempotent?

Interview answer for how do you make queued jobs idempotent? with syntax and a practical Laravel/PHP pattern.

Answer

How do you make queued jobs idempotent? is a key concept in testing, queues, caching, and deployment. In Laravel, prefer framework-supported conventions, clear separation of responsibilities, and explicit validation and authorization. Choose the implementation based on the application's requirements, then verify behavior with tests and review performance and security implications. The exact APIs can differ by Laravel and PHP version, so check the version used by your project.

Syntax

Cache::remember('products:featured', 300, fn () => Product::featured()->get());

Example

Cache expensive, reusable results for a bounded period and define an explicit invalidation policy.

Code example

use Illuminate\Support\Facades\Cache;

$products = Cache::remember('products:featured', now()->addMinutes(5), function () {
    return Product::query()
        ->where('featured', true)
        ->orderBy('name')
        ->get();
});

Diagram

Request/job → Cache or queue check → Cache hit / worker execution → Database/service → Result + metrics

Key Points

  • Know the purpose and trade-offs, not just the syntax.
  • Keep validation, authorization, and business logic clearly separated.
  • Prefer framework features and parameterized queries over custom implementations.
  • Test success paths, invalid input, unauthorized access, and failure cases.

Share this question bank

Send this page to someone preparing for an interview.