Powered by Thakur Technologies

    Laravel backend development interview questions with answers

    Intermediate & Advanced Level backend development interview Questions with Answers

    1. What is the purpose of service providers in Laravel?

    Answer: Service providers are the central place for bootstrapping Laravel applications. They bind services into the service container.

    To create a service provider:

    php artisan make:provider MyServiceProvider

    Then, register it in config/app.php:

    'providers' => [

        App\Providers\MyServiceProvider::class,

    ];

    Inside MyServiceProvider.php:

    public function register()

    {

        $this->app->bind('MyService', function () {

            return new \App\Services\MyService();

        });

    }

    2. How does Laravel handle dependency injection?

    Answer: Laravel resolves dependencies automatically via the Service Container.

    Example:

    class UserController extends Controller

    {

        protected $userService;


        public function __construct(UserService $userService)

        {

            $this->userService = $userService;

        }


        public function index()

        {

            return $this->userService->getAllUsers();

        }

    }


    Laravel automatically resolves UserService from the service container.

    3. What are Laravel facades, and how do they work?

    Answer: Facades provide a static-like interface to classes in the service container.

    Example: Creating a custom facade:

    namespace App\Facades;

    use Illuminate\Support\Facades\Facade;


    class MyServiceFacade extends Facade

    {

        protected static function getFacadeAccessor()

        {

            return 'MyService';

        }

    }

    Register in config/app.php:

    'aliases' => [

        'MyService' => App\Facades\MyServiceFacade::class,

    ];


    Usage:

    MyService::doSomething();


    4. Explain the difference between hasManyThrough and hasOneThrough relationships in Eloquent.

    Answer:

    • hasManyThrough: A one-to-many relationship through an intermediary table.

    • hasOneThrough: A one-to-one relationship through an intermediary table.

    Example:

    class Country extends Model

    {

        public function posts()

        {

            return $this->hasManyThrough(Post::class, User::class);

        }

    }


    Here, Country has many Posts through User.

    5. What is a Laravel Observer, and when should you use it?


    Answer: Observers listen for model events such as creating, updating, deleting.

    Create an observer:

    php artisan make:observer UserObserver --model=User

    Inside UserObserver.php:

    public function creating(User $user)

    {

        $user->uuid = Str::uuid();

    }

    Register in EventServiceProvider.php:

    protected $observers = [

        User::class => UserObserver::class,

    ];


    6. How can you prevent mass assignment vulnerabilities in Laravel?

    Answer: Define $fillable or $guarded in models.

    protected $fillable = ['name', 'email', 'password'];

    Or use $guarded to block specific fields:

    protected $guarded = ['admin'];


    7. What is the difference between policies and gates in Laravel authorization?

    Answer:

    • Gates: Simple authorization logic using closures.

    Policies: Encapsulated authorization for models.

    Gate example:

    Gate::define('edit-post', function ($user, $post) {

        return $user->id === $post->user_id;

    });


    Usage:

    if (Gate::allows('edit-post', $post)) { /* ... */ }



    Advanced Level Questions

    08. Explain how Laravel’s job batching works and how you would implement it.

    Answer: Batching allows grouping jobs and handling them as a batch.

    use Illuminate\Bus\Batch;

    use Illuminate\Support\Facades\Bus;


    $batch = Bus::batch([

        new ProcessOrderJob(1),

        new ProcessOrderJob(2)

    ])->dispatch();


    09. What is event broadcasting in Laravel, and how do you implement it using WebSockets?

    Answer: Event broadcasting allows real-time updates via WebSockets.

    Install Pusher: composer require pusher/

    pusher-php-server


    1. Configure .env:

    BROADCAST_DRIVER=pusher


    2. Create an event:

    php artisan make:event MessageSent


    3. Dispatch the event:

    broadcast(new MessageSent($message));


    10. What is the purpose of Lazy Loading vs. Eager Loading in Eloquent ORM?

    Answer:

    Lazy Loading: Loads related data when accessed.

    Eager Loading: Loads related data upfront.

    Example:

    // Lazy Loading

    $user = User::find(1);

    $posts = $user->posts; // Runs extra query


    // Eager Loading

    $user = User::with('posts')->find(1); // Single query


    11. How does Laravel handle API rate limiting?

    Answer:

    Using throttle middleware:

    Route::middleware('throttle:60,1')->get('/api/data', function () {

        return response()->json(['message' => 'Success']);

    });

    12. Explain the concept of Headless Laravel and its benefits.

    Answer:

    Headless Laravel is used as a backend API without a frontend.

    Benefits:

    • Better API performance.

    • Can be used with frontend frameworks like React, Vue, etc.

    13. What is the difference between singleton, scoped, and transient bindings in the Laravel service container?

    Answer:

    $this->app->singleton(Service::class, function () {

        return new Service();

    }); // Single instance


    $this->app->scoped(Service::class, function () {

        return new Service();

    }); // Per request


    $this->app->bind(Service::class, function () {

        return new Service();

    }); // New instance every time


    14. How do you secure an API in Laravel using Laravel Passport or Sanctum?

    Answer: Install and configure Laravel Sanctum:

    composer require laravel/sanctum

    php artisan vendor:publish --provider="Laravel\Sanctum\

    SanctumServiceProvider"


    php artisan migrate


    Protect routes:

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

        return $request->user();

    });

    15. How do you implement repository patterns in Laravel?

    Answer:

    1. Create an interface:

    interface UserRepositoryInterface {

        public function all();

    }


    1. Implement the interface:

    class UserRepository implements UserRepositoryInterface {

        public function all() {

            return User::all();

        }

    }


    1. Bind in AppServiceProvider.php:

    $this->app->bind(UserRepositoryInterface::class, UserRepository::class);








    Responsive Ad Box


    Frequently Asked Questions (FAQs)

    You should focus on service providers, dependency injection, middleware, Eloquent relationships, queues, event broadcasting, authentication, and API security using Laravel Passport or Sanctum.
    Use eager loading (with()), indexing in the database, caching (cache() helper), database transactions, and query optimization tools like Laravel Debugbar to analyze queries.
    You can use Laravel Sanctum for token-based authentication, middleware for route protection, API rate limiting, and signed URLs to prevent unauthorized access.
    Laravel uses queue drivers like Redis, database, and Beanstalk. You can dispatch jobs using dispatch(), process them with workers (php artisan queue:work), and monitor them via Laravel Horizon.
    Some common mistakes include not using eager loading (causing N+1 query issues), improper validation handling, not using the service container efficiently, hardcoding configurations instead of using .env, and not handling exceptions properly.







    Like

    Share


    # Tags

    Listing your voice

    Powered by Thakur Technologies