100+ Laravel Interview Question for Job

Laravel Interview Question: The Ultimate 2025 Guide

Introduction

Welcome to our 100+ laravel Interview Question for Job. This 3000-word, and highly updated blog covers 100 detailed Laravel interview question , each answered thoroughly with extensive code examples, conceptual explanations, and best practices. Whether you’re a junior developer or a senior engineer, this professional, reader-engaging resource will equip you with the confidence to excel in your next Laravel interview.

Table of Contents

SectionQuestions Covered
Basics & SetupQ1–Q10
Routing & MiddlewareQ11–Q20
Blade & ViewsQ21–Q30
Eloquent & DatabaseQ31–Q40
AuthenticationQ41–Q50
Artisan & CLIQ51–Q60
Advanced ArchitectureQ61–Q70
PerformanceQ71–Q80
Testing & DebuggingQ81–Q90
Expert & ConceptualQ91–Q100

Basics & Setup

1. What is Laravel?

Laravel is an open-source PHP framework that implements the MVC pattern, offering expressive syntax, built-in tools for authentication, routing, sessions, and caching, and a thriving ecosystem (Forge, Vapor, Envoy).


// Basic route example
Route::get('/', function () {
    return view('welcome');
});

2. Why choose Laravel over other frameworks?

  • Expressive Syntax: Elegant and readable code.
  • Ecosystem: Official packages: Horizon, Nova.
  • Community & Documentation: Active support and tutorials.

3. Describe Laravel’s directory structure.

  • app/: Core application code (Models, Controllers, Services).
  • bootstrap/: Framework bootstrap files.
  • config/: Configuration.
  • database/: Migrations, seeders, factories.
  • public/: Front controller and assets.
  • resources/: Views, raw assets.
  • routes/: Route definitions.
  • storage/: Logs, cache.
  • tests/: Automated tests.

4. How to install Laravel via Composer?


composer create-project --prefer-dist laravel/laravel laravel-interview

5. Explain the purpose of the .env file.

Stores environment-specific configuration (DB credentials, API keys). Loaded at runtime by vlucas/phpdotenv.

6. What is the role of bootstrap/app.php?

Boots the framework, registers service providers, and returns the application instance.

7. How to configure multiple database connections?


DB_CONNECTION=mysql
DB_DATABASE=main_db
DB_SECONDARY_CONNECTION=pgsql
DB_SECONDARY_DATABASE=analytics_db

// config/database.php
'connections' => [
  'mysql' => [...],
  'analytics' => [
    'driver' => 'pgsql',
    'database' => env('DB_SECONDARY_DATABASE'),
    // ...
  ],
],

8. What is Artisan?

Laravel’s command-line interface for generating code, running tasks, and managing the application.

9. List three Artisan commands for database management.

  • php artisan migrate
  • php artisan migrate:rollback
  • php artisan migrate:refresh

10. How to create a custom Artisan command?


php artisan make:command SendWeeklyReport

// app/Console/Commands/SendWeeklyReport.php
namespace App\Console\Commands;

use Illuminate\Console\Command;

class SendWeeklyReport extends Command
{
    protected $signature = 'report:weekly';
    protected $description = 'Send weekly report to admins';

    public function handle()
    {
        // Reporting logic
        $this->info('Weekly report sent.');
    }
}

Routing & Middleware

11. Explain basic route definition.


Route::get('/users', [UserController::class, 'index']);

12. How to pass parameters to routes?


Route::get('/user/{id}', function ($id) {
    return User::findOrFail($id);
});

13. What is route model binding?

Automatically injects model instances based on route parameters.


Route::get('/user/{user}', function (App\Models\User $user) {
    return $user->email;
});

14. Differentiate between HTTP verbs in routes.

  • GET for fetching data.
  • POST for creating resources.
  • PUT/PATCH for updates.
  • DELETE for removals.

15. How to name routes and generate URLs?


Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
// Generate URL
route('dashboard');

16. What is middleware in Laravel?

Filters HTTP requests entering the application (e.g., authentication, logging).

17. How to create custom middleware?


php artisan make:middleware EnsureUserIsActive

public function handle($request, Closure $next)
{
    if (! $request->user()->is_active) {
        return redirect('inactive');
    }
    return $next($request);
}

18. How to register middleware?

In app/Http/Kernel.php, add to $middleware (global) or $routeMiddleware (assignable).

19. How to apply middleware to routes?


Route::get('/settings', [SettingsController::class, 'index'])
     ->middleware(['auth', 'active']);

20. What is middleware priority?

Controls the execution order via the $middlewarePriority array in Kernel.

100+ laravel Interview Question for Job

Blade & Views

21. What is Blade?

Laravel’s templating engine that compiles to optimized PHP code.

22. How to use Blade directives @if and @foreach?


@if($user)
  <p>Welcome, {{ $user->name }}</p>
@endif

@foreach($posts as $post)
  <h2>{{ $post->title }}</h2>
@endforeach

23. What is the difference between {{ }} and {!! !!}?

{{ }} escapes HTML; {!! !!} outputs raw HTML.

24. How to create layouts with @yield and @extends?


{{-- layouts/app.blade.php --}}
<html>
<body>
  @yield('content')
</body>
</html>

{{-- welcome.blade.php --}}
@extends('layouts.app')
@section('content')
  <h1>Hello World</h1>
@endsection

25. How to include partial views?


@include('partials.header')

26. What are Blade components and slots?


{{-- components/alert.blade.php --}}
<div class="alert alert-{{ $type }}">
  {{ $slot }}
</div>

{{-- usage --}}
<x-alert type="error">
  Something went wrong!
</x-alert>

27. How to pass data to views from controllers?


public function show()
{
  $users = User::all();
  return view('users.index', compact('users'));
}

28. What is inline Blade templating?

Using @props for defining component properties.

29. How to use conditional directives @auth and @guest?


@auth
  <p>Logged in</p>
@endauth

@guest
  <p>Please login</p>
@endguest

30. How to handle loops with empty states?


@forelse($comments as $comment)
  <p>{{ $comment->body }}</p>
@empty
  <p>No comments yet.</p>
@endforelse

Eloquent & Database

31. What is Eloquent ORM?

Laravel’s ActiveRecord implementation for working with your database.

32. How to define a one-to-many relationship?


// Post.php
public function comments()
{
    return $this->hasMany(Comment::class);
}

33. How to define many-to-many relationships?


// User.php
public function roles()
{
    return $this->belongsToMany(Role::class);
}

34. What is mass assignment and how to protect models?

Use $fillable or $guarded properties in models:


protected $fillable = ['title', 'body'];

35. How to create accessors and mutators?


// Accessor
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

// Mutator
public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value);
}

36. What are query scopes?

Reusable query fragments in models:


public function scopeActive($query)
{
    return $query->where('active', 1);
}
// Usage
User::active()->get();

37. When to use Query Builder vs Eloquent?

Use Query Builder (DB::table) for complex joins or performance-critical queries.

38. How to eager load relationships?


$users = User::with('posts.comments')->get();

39. How to paginate results?


$users = User::paginate(15);

40. How to handle database transactions?


DB::transaction(function () {
    // multiple related queries
});

Authentication

41. What built-in authentication scaffolding exists?

Options: Breeze, Jetstream, Laravel UI for quick setup.

42. How to customize authentication guards?

Define new guards and providers in config/auth.php.

43. Explain Auth::attempt().

Validates credentials and logs in user:


if (Auth::attempt(['email' => $email, 'password' => $password])) {
    return redirect()->intended('dashboard');
}

44. How does Laravel hash passwords?

Uses Bcrypt via the Hash facade:


$hash = Hash::make('secret');

45. Implement “remember me” functionality.

Pass true to attempt():


Auth::attempt($credentials, true);

46. How to verify user emails?

Implement MustVerifyEmail on User model and use verified middleware.

47. How to reset passwords?

Built-in traits: ResetsPasswords and mailables configured via Auth::routes().

48. Implement two-factor authentication (2FA).

Use Fortify or Passport with TOTP or SMS providers.

49. Social authentication with Socialite.


return Socialite::driver('github')->redirect();
$user = Socialite::driver('github')->user();

50. Token-based auth with Sanctum.

Generate SPA tokens:


$token = $request->user()->createToken('api-token');

Artisan & CLI

51. List five common Artisan commands.

  • php artisan route:list
  • php artisan config:cache
  • php artisan make:controller
  • php artisan migrate
  • php artisan tinker

52. How to schedule recurring tasks?

In app/Console/Kernel.php:


protected function schedule(Schedule $schedule)
{
    $schedule->command('report:weekly')->mondays()->at('8:00');
}

53. What is Tinker?

REPL for interacting with your application:


php artisan tinker
>>> User::count();

54. How to use seeders and factories?


php artisan make:seeder UserSeeder
php artisan db:seed --class=UserSeeder

User::factory()->count(50)->create();

55. Clearing caches via Artisan.


php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear

56. How to make database migrations?


php artisan make:migration add_status_to_users --table=users

57. How to manage queues with Artisan?


php artisan queue:work
php artisan queue:failed
php artisan queue:retry all

58. Publish package assets.


php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"

59. Optimize class loader.


php artisan optimize

60. Generate application key.


php artisan key:generate

Advanced Architecture

61. What is the IoC container?

Manages class dependencies and performs dependency injection.

62. How to bind interfaces to implementations?


// AppServiceProvider.php
$this->app->bind(\App\Contracts\PaymentGateway::class, \App\Services\StripeGateway::class);

63. What are Facades?

Static proxies to underlying classes in the service container.

64. How to implement the Repository pattern?

Create repository interfaces and concrete classes, bind in a service provider.

65. What are Events & Listeners?


php artisan make:event OrderShipped
php artisan make:listener SendShipmentNotification --event=OrderShipped

66. Explain broadcasting.

Real-time events via Pusher or WebSocket drivers using broadcastOn().

67. API Resource classes.


php artisan make:resource UserResource

return new UserResource(User::find($id));

68. Rate limiting with middleware.


Route::middleware('throttle:60,1')->group(...);

69. Service providers lifecycle.

register() first (bindings), then boot() (event listeners).

70. How to build a Laravel package?

Directory structure, composer.json, service provider, facade, config publishing.


Performance

71. How to optimize queries?

Use indexes, explain(), avoid N+1 by eager loading.

72. Caching strategies:

  • Query caching using remember()
  • Response caching
  • View caching

73. Integrate Redis with Laravel.

Set CACHE_DRIVER=redis and QUEUE_CONNECTION=redis in .env.

74. How to monitor queues with Horizon?

Install laravel/horizon, configure dashboards for Redis queues.

75. What is OPcache and how to enable it?

PHP extension caching compiled bytecode, configured via php.ini.

76. Minify assets with Laravel Mix.


mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .version();

77. Load testing tools.

  • Apache Bench (ab)
  • JMeter
  • Siege

78. Profile with Telescope.

Install laravel/telescope, view queries, jobs, exceptions in UI.

79. Database replication setup.

Configure read and write hosts in config/database.php.

80. Asynchronous processing patterns.

Use Jobs for background tasks, Events for decoupled logic.

Testing & Debugging

81. How to write unit tests?


php artisan make:test UserTest --unit

public function test_user_creation()
{
  $user = User::factory()->create();
  $this->assertDatabaseHas('users', ['id' => $user->id]);
}

82. How to write feature tests?


php artisan make:test LoginTest

public function test_user_can_login()
{
  $user = User::factory()->create(['password' => bcrypt($pass = 'test123')]);
  $response = $this->post('/login', ['email' => $user->email, 'password' => $pass]);
  $response->assertRedirect('/home');
}

83. Mock external services.


Http::fake([
  'api.example.com/*' => Http::response(['data' => []])
]);

84. Browser tests with Dusk.


php artisan dusk:install
php artisan dusk

85. Use Debugbar for profiling.

Install barryvdh/laravel-debugbar; view queries and memory usage.

86. Exception handling in render().

Customize the render() method in Handler.php to format responses.

87. Custom log channels.

Configure in config/logging.php and use:


Log::channel('slack')->info('Error');

88. HTTP client testing.

Use Http::fake() and Http::assertSent() for request assertions.

89. Database migrations refresh in tests.

Use RefreshDatabase trait for clean test state.

90. Parallel testing.


php artisan test --parallel

Expert & Conceptual

91. What is Laravel Octane?

Runs Laravel on Swoole or RoadRunner for high-performance, in-memory applications.

92. Implement WebSockets with Echo.

Configure broadcasting, set up Echo server, and broadcast events:


event(new OrderShipped($order));

93. Zero-downtime deployments.

Use atomic releases with Envoy or tools like Deployer.

94. CI/CD pipeline example (GitHub Actions).


name: Laravel CI
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: 8.1
      - run: composer install
      - run: php artisan migrate --env=testing
      - run: php artisan test

95. Serverless Laravel with Vapor.

Deploy to AWS Lambda using vapor.yml and the Vapor CLI.

96. Containerization with Docker & Kubernetes.

Example setup includes a Dockerfile and k8s.yml for services and deployments.

97. Integrate GraphQL using Lighthouse.

Install nuwave/lighthouse, and define schema in graphql/schema.graphql.

98. Domain-Driven Design (DDD) in Laravel.

Structure your application by domain: entities, value objects, aggregates, and repositories.

99. Multi-tenancy approaches.

Use single-database with tenant_id or multiple databases per tenant (e.g., Spatie Multitenancy).

100. Laravel security best practices.

  • Always escape output with {{ }} to prevent XSS.
  • Use Eloquent or prepared statements to prevent SQL injection.
  • Enable CSRF protection using @csrf.
  • Validate and sanitize user input rigorously.

DSA & Algorithmic Challenges for Laravel

In modern Laravel applications, integrating efficient data structures and algorithms (DSA) can significantly boost performance and maintainability. Below is a set of 10 professional DSA-focused questions tailored for Laravel interviews, complete with context and sample code where applicable.

1. Implement an LRU Cache Service in Laravel

Design a singleton service in Laravel that maintains an LRU (Least Recently Used) cache using a doubly linked list and hash map. Provide methods get($key) and put($key, $value).


// App/Services/LruCacheService.php
class LruCacheService
{
    private $capacity;
    private $map; // associative array for node references
    private $head; // dummy head of linked list
    private $tail; // dummy tail of linked list

    public function __construct($capacity = 50)
    {
        $this->capacity = $capacity;
        $this->map = [];
        $this->head = new Node(null, null);
        $this->tail = new Node(null, null);
        $this->head->next = $this->tail;
        $this->tail->prev = $this->head;
    }

    public function get($key)
    {
        if (!isset($this->map[$key])) return null;
        $node = $this->map[$key];
        $this->moveToHead($node);
        return $node->value;
    }

    public function put($key, $value)
    {
        if (isset($this->map[$key])) {
            $node = $this->map[$key];
            $node->value = $value;
            $this->moveToHead($node);
        } else {
            $node = new Node($key, $value);
            $this->map[$key] = $node;
            $this->addNode($node);
            if (count($this->map) > $this->capacity) {
                $removed = $this->popTail();
                unset($this->map[$removed->key]);
            }
        }
    }

    // addNode, removeNode, moveToHead, popTail methods omitted for brevity
}

2. Flatten Nested Configuration Arrays

Write a recursive algorithm in a Laravel helper to flatten a nested configuration array into dot-notated keys (e.g., ['app' => ['name'=>'x']] to ['app.name'=>'x']).

3. Detect Cycles in Route Graph

Given a graph of application routes (nodes) and redirections (edges), implement cycle detection using DFS in a console command to avoid infinite redirect loops.

4. Hierarchical Category Retrieval with Segment Trees

Design a Segment Tree to perform range sum queries over Eloquent models representing category weights. Provide methods for building and querying the tree.

5. Implement Trie for URL Autocomplete

Create a Trie data structure as a Laravel service to index and autocomplete registered routes based on prefix input.

6. Optimize Bulk Insert with Divide & Conquer

Write a divide-and-conquer strategy in a job to batch-insert millions of records into the database efficiently, handling failures and retries.

7. Implement Topological Sort for Task Scheduling

In a Laravel queue job, given tasks with dependencies, implement Kahn’s algorithm to determine execution order.

8. Circular Dependency Resolution in Service Container

Explain how you would detect and resolve circular dependencies when binding interfaces in the Laravel IoC container.

9. Rolling Hash for Content Versioning

Implement a rolling hash (e.g., Rabin-Karp) in a middleware to detect changes in request payloads for caching invalidation.

10. Sliding Window for Rate Limiting

Design a sliding window algorithm in middleware to enforce API rate limits in a Redis-backed store.


Intermediate Level Challenges

Q1: Flatten Nested Arrays into Dot-Notation Keys

Question: How would you recursively flatten a multidimensional PHP array into a single-level array using dot-notation for keys?


if (! function_exists('array_dot')) {
    function array_dot(array $array, string $prepend = ''): array {
        $result = [];
        foreach ($array as $key => $value) {
            $newKey = $prepend . $key;
            if (is_array($value)) {
                $result += array_dot($value, $newKey . '.');
            } else {
                $result[$newKey] = $value;
            }
        }
        return $result;
    }
}

$config = [
    'app' => ['name' => 'MyApp', 'debug' => true],
    'mail' => ['driver' => 'smtp']
];
$flattened = array_dot($config);
// Output:
// [
//   'app.name' => 'MyApp',
//   'app.debug' => true,
//   'mail.driver' => 'smtp'
// ]
    

Q2: Implement an LRU Cache Service

Question: Design a singleton Laravel service that provides get($key) and put($key, $value) using an LRU (Least Recently Used) eviction policy.


namespace App\Services;

class LruCache {
    private int $capacity;
    private array $map = [];
    private Node $head;
    private Node $tail;

    public function __construct(int $capacity = 100) {
        $this->capacity = $capacity;
        $this->head = new Node(null, null);
        $this->tail = new Node(null, null);
        $this->head->next = $this->tail;
        $this->tail->prev = $this->head;
    }

    public function get(string $key) {
        if (!isset($this->map[$key])) return null;
        $node = $this->map[$key];
        $this->remove($node);
        $this->addToFront($node);
        return $node->value;
    }

    public function put(string $key, $value): void {
        if (isset($this->map[$key])) {
            $node = $this->map[$key];
            $node->value = $value;
            $this->remove($node);
            $this->addToFront($node);
        } else {
            $node = new Node($key, $value);
            $this->map[$key] = $node;
            $this->addToFront($node);
            if (count($this->map) > $this->capacity) {
                $lru = $this->tail->prev;
                $this->remove($lru);
                unset($this->map[$lru->key]);
            }
        }
    }

    private function remove(Node $node): void {
        $node->prev->next = $node->next;
        $node->next->prev = $node->prev;
    }

    private function addToFront(Node $node): void {
        $node->next = $this->head->next;
        $node->prev = $this->head;
        $this->head->next->prev = $node;
        $this->head->next = $node;
    }
}

class Node {
    public ?string $key;
    public $value;
    public ?Node $prev = null;
    public ?Node $next = null;

    public function __construct(?string $key, $value) {
        $this->key = $key;
        $this->value = $value;
    }
}
    

Q3: Detect Cycles in a Redirect Graph

Question: Given a map of routes to their redirect targets, write a console command to detect cycles.


namespace App\Console\Commands;

use Illuminate\Console\Command;

class DetectRedirectCycle extends Command {
    protected $signature = 'redirect:detect-cycles';
    protected $description = 'Detect redirect loops';
    private $graph = ['/a' => '/b', '/b' => '/c', '/c' => '/a'];

    public function handle() {
        $visited = [];
        $recStack = [];

        foreach (array_keys($this->graph) as $node) {
            if ($this->dfs($node, $visited, $recStack)) {
                $this->error("Cycle detected starting at {$node}");
                return 1;
            }
        }

        $this->info('No cycles detected.');
    }

    private function dfs($node, &$visited, &$recStack) {
        if (!isset($visited[$node])) {
            $visited[$node] = true;
            $recStack[$node] = true;

            $neighbor = $this->graph[$node] ?? null;
            if ($neighbor && ((!isset($visited[$neighbor]) && $this->dfs($neighbor, $visited, $recStack)) || isset($recStack[$neighbor]))) {
                return true;
            }
        }
        unset($recStack[$node]);
        return false;
    }
}
    

Advanced Level Challenges

Q16: Divide-and-Conquer Bulk Insert Job

Question: How would you insert millions of records efficiently in a Laravel job, handling failures and retries via a divide-and-conquer strategy?

Answer: Split data into chunks, dispatch sub-jobs, and use transactions:


class BulkInsertJob implements ShouldQueue {
    use Dispatchable, InteractsWithQueue, Queueable;

    private array $rows;
    public function __construct(array $rows) {
        $this->rows = $rows;
    }
    public function handle() {
        if (count($this->rows) > 10000) {
            $mid = intdiv(count($this->rows), 2);
            dispatch(new BulkInsertJob(array_slice($this->rows, 0, $mid)));
            dispatch(new BulkInsertJob(array_slice($this->rows, $mid)));
            return;
        }
        DB::transaction(function() {
            DB::table('big_table')->insert($this->rows);
        });
    }
}
    

Q17: Sliding-Window Maximum

Question: Given an array of integers and window size k, compute the maximum for each sliding window in O(n).

Answer: Use a deque to store indices of potential max candidates.


function slidingWindowMax(array $nums, int $k): array {
    $result = [];
    $deque = [];
    foreach ($nums as $i => $num) {
        while ($deque && $deque[0] <= $i - $k) array_shift($deque);
        while ($deque && $nums[end($deque)] <= $num) array_pop($deque);
        $deque[] = $i;
        if ($i >= $k - 1) $result[] = $nums[$deque[0]];
    }
    return $result;
}

// Usage:
print_r(slidingWindowMax([1,3,-1,-3,5,3,6,7], 3));
    

Q18: Union-Find (Disjoint Set) for Grouping Models

Question: Implement a Disjoint Set to cluster related models (e.g., friend groups).


class DisjointSet {
    private array $parent = [];
    private array $rank = [];

    public function makeSet(array $elements) {
        foreach ($elements as $e) {
            $this->parent[$e] = $e;
            $this->rank[$e] = 0;
        }
    }

    public function find($x) {
        if ($this->parent[$x] !== $x) {
            $this->parent[$x] = $this->find($this->parent[$x]);
        }
        return $this->parent[$x];
    }

    public function union($x, $y) {
        $rx = $this->find($x);
        $ry = $this->find($y);
        if ($rx === $ry) return;

        if ($this->rank[$rx] < $this->rank[$ry]) {
            $this->parent[$rx] = $ry;
        } else {
            $this->parent[$ry] = $rx;
            if ($this->rank[$rx] === $this->rank[$ry]) {
                $this->rank[$rx]++;
            }
        }
    }
}

// Usage:
$ds = new DisjointSet();
$ds->makeSet([1,2,3,4]);
$ds->union(1,2);
$ds->union(3,4);
    

Q19: Levenshtein Edit Distance

Question: Compute Levenshtein distance between two strings in PHP, optimized with only two rows of DP.


function editDistance(string $s, string $t): int {
    $m = strlen($s); $n = strlen($t);
    $prev = range(0, $n);
    for ($i = 1; $i <= $m; $i++) {
        $curr = [$i];
        for ($j = 1; $j <= $n; $j++) {
            $delete = $prev[$j] + 1;
            $insert = $curr[$j-1] + 1;
            $replace = $prev[$j-1] + ($s[$i-1] !== $t[$j-1]);
            $curr[] = min($delete, $insert, $replace);
        }
        $prev = $curr;
    }
    return $prev[$n];
}

// Usage:
echo editDistance('kitten','sitting'); // 3
    

Q20: Minimum Cuts for Palindrome Partitioning

Question: Given a string, return the minimum number of cuts needed to partition it such that every substring is a palindrome.


function minCut(string $s): int {
    $n = strlen($s);
    $isPal = array_fill(0, $n, array_fill(0, $n, false));
    for ($i = $n-1; $i >= 0; $i--) {
        for ($j = $i; $j < $n; $j++) {
            $isPal[$i][$j] = ($s[$i] == $s[$j]) && ($j - $i < 2 || $isPal[$i+1][$j-1]);
        }
    }

    $cuts = array_fill(0, $n, PHP_INT_MAX);
    for ($i = 0; $i < $n; $i++) {
        if ($isPal[0][$i]) {
            $cuts[$i] = 0;
        } else {
            for ($j = 0; $j < $i; $j++) {
                if ($isPal[$j+1][$i] && $cuts[$j] + 1 < $cuts[$i]) {
                    $cuts[$i] = $cuts[$j] + 1;
                }
            }
        }
    }
    return $cuts[$n-1];
}

// Usage:
echo minCut("aab"); // 1
    

External Resources

Discover the Best AI Tools for Developers 2025 – a curated guide to cutting-edge tools that boost your coding productivity.

Here are some valuable links to deepen your Laravel expertise:

Leave a Comment

Your email address will not be published. Required fields are marked *