Laravel PHP Questions & Answers set-01

Objectives: Laravel PHP Questions & Answers

Laravel PHP Questions & Answers (set1)

Laravel PHP Interview Questions & Deep Answers (1–13)

1. What is Laravel and why is it popular?

Laravel is a free, open-source PHP web framework created by Taylor Otwell. It follows the MVC (Model-View-Controller) architecture and simplifies complex tasks like routing, sessions, caching, and authentication.

Why Laravel is Popular:
  • Readable and elegant syntax.
  • Blade templating engine.
  • Built-in authentication, queues, and email systems.
  • Active community and excellent documentation.

2. What is Routing in Laravel?

Routing in Laravel maps web requests to specific functions or controllers. It’s defined inside the routes/web.php file.

// Basic Route
Route::get('/about', function () {
    return view('about');
});

You can also use controllers:

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

3. Explain Route::get(), Route::post(), and Route::match()

  • Route::get() handles HTTP GET requests.
  • Route::post() handles HTTP POST (form submission).
  • Route::match() accepts multiple methods.
// Example
Route::get('/login', [AuthController::class, 'showForm']);
Route::post('/login', [AuthController::class, 'processLogin']);
Route::match(['get', 'post'], '/register', [UserController::class, 'register']);

4. What is Middleware in Laravel?

Middleware filters HTTP requests entering your application. It can check if a user is logged in, or has certain roles.

// Assign middleware to a route
Route::get('/dashboard', function () {
    return 'Welcome!';
})->middleware('auth');

You can create your own middleware:

php artisan make:middleware CheckAdmin

5. Difference between invokable, resource, and normal controller

  • Normal Controller has multiple methods (index, show, create, etc).
  • Invokable Controller has only one method: __invoke().
  • Resource Controller uses Laravel’s built-in methods like index(), store(), update(), etc.
// Resource route
Route::resource('posts', PostController::class);

// Invokable route
Route::get('/report', ReportController::class);

6. What is FormRequest in Laravel?

FormRequest is a dedicated class used to handle validation logic cleanly, outside the controller.

// Create request
php artisan make:request StoreUserRequest
// Inside StoreUserRequest.php
public function rules()
{
  return [
    'name' => 'required|string|max:255',
    'email' => 'required|email|unique:users',
  ];
}

Then in the controller:

public function store(StoreUserRequest $request) {
  // Already validated!
}

7. What are the Eloquent Relationships?

  • hasOne() – One-to-One
  • hasMany() – One-to-Many
  • belongsTo() – Inverse of hasOne/hasMany
  • belongsToMany() – Many-to-Many
  • morphMany() – Polymorphic relationship
// Post has many Comments
public function comments()
{
  return $this->hasMany(Comment::class);
}

8. Example: Fetch posts of a user with their comments

$user = User::with('posts.comments')->find($id);

foreach ($user->posts as $post) {
  echo $post->title;
  foreach ($post->comments as $comment) {
    echo $comment->body;
  }
}

9. What are Migrations in Laravel?

Migrations are version control for your database. You define database tables and changes using PHP.

php artisan make:migration create_posts_table
Schema::create('posts', function (Blueprint $table) {
  $table->id();
  $table->string('title');
  $table->text('body');
  $table->timestamps();
});

10. DB::table() vs Eloquent Model::query()

  • DB::table() – Query Builder, more manual and lower-level.
  • Model::query() – Eloquent ORM, object-oriented, easier to work with relationships.
// Using DB
$users = DB::table('users')->where('active', 1)->get();

// Using Eloquent
$users = User::where('active', 1)->get();

11. What is a Seeder and Factory in Laravel?

Factory generates fake data. Seeder inserts it into the database.

// Create factory and seeder
php artisan make:factory UserFactory
php artisan make:seeder UserSeeder
// In seeder
public function run()
{
  \App\Models\User::factory(10)->create();
}
php artisan db:seed --class=UserSeeder

12. Auth::attempt(), Auth::login(), Auth::check() – What’s the difference?

  • Auth::attempt() – Tries to log in using credentials (email/password).
  • Auth::login($user) – Manually logs in a user instance.
  • Auth::check() – Checks if a user is logged in.
if (Auth::attempt(['email' => $email, 'password' => $password])) {
  return redirect('/dashboard');
}

13. How to use Laravel Sanctum for API token authentication?

Laravel Sanctum provides simple API token-based authentication for SPAs and mobile apps.

  1. Install Sanctum: composer require laravel/sanctum
  2. Publish config: php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  3. Migrate: php artisan migrate
  4. Use HasApiTokens in User model.
$user = User::where('email', $request->email)->first();

if ($user && Hash::check($request->password, $user->password)) {
  $token = $user->createToken('api-token')->plainTextToken;
  return response()->json(['token' => $token]);
}

14. What are Gates and Policies in Laravel?

Gates and Policies are Laravel’s ways to handle authorization (not authentication).

  • Gate is a closure-based authorization check.
  • Policy is a class that organizes authorization logic for a model.
// Gate in AuthServiceProvider
Gate::define('update-post', function ($user, $post) {
  return $user->id === $post->user_id;
});

// Using Gate
if (Gate::allows('update-post', $post)) {
  // Allow update
}
// Policy Method (PostPolicy.php)
public function update(User $user, Post $post)
{
  return $user->id === $post->user_id;
}
// Usage
$this->authorize('update', $post);

15. What is Artisan in Laravel?

Artisan is Laravel’s command-line interface (CLI). It helps automate tasks like generating files, running migrations, clearing cache, and more.

php artisan make:model Product -mcr

This command creates a model, migration, and controller for Product.

// Create custom command
php artisan make:command GreetUser

Inside handle() method of command:

$name = $this->ask('What is your name?');
$this->info("Hello, $name!");

16. What is the purpose of Service Providers in Laravel?

Service providers bootstrap your Laravel application. They register bindings and perform startup logic.

public function register()
{
  $this->app->bind(MyService::class, function () {
    return new MyService();
  });
}
public function boot()
{
  // Things to do after all services are registered
}

17. What are Jobs, Events, and Listeners in Laravel?

- Job: A queued task (e.g., send email).
- Event: An action that happened (e.g., OrderPlaced).
- Listener: What should happen when event occurs.

// Event: OrderPlaced
event(new OrderPlaced($order));
// Listener
public function handle(OrderPlaced $event)
{
  Mail::to($event->order->user)->send(new OrderConfirmation());
}
// Dispatch Job
SendWelcomeEmail::dispatch($user);

18. Why and when should you use Queues in Laravel?

Queues help defer time-consuming tasks like sending emails or processing video uploads. They improve user experience by keeping the app responsive.

// Create a job
php artisan make:job SendReport
dispatch(new SendReport($reportData));

Then run:

php artisan queue:work

19. Difference between Unit Test and Feature Test

- Unit Test: Tests one method/class in isolation.
- Feature Test: Tests the whole request lifecycle (routes, middleware, etc).

// Unit Test
public function testDiscountCalculation()
{
  $this->assertEquals(90, Price::applyDiscount(100, 10));
}
// Feature Test
public function testGuestCannotAccessDashboard()
{
  $response = $this->get('/dashboard');
  $response->assertRedirect('/login');
}

20. Feature test for guest restriction to /dashboard

public function test_guest_cannot_access_dashboard()
{
  $response = $this->get('/dashboard');
  $response->assertStatus(302);
  $response->assertRedirect('/login');
}

21. What are Blade Components and Slots?

Blade components allow reusable UI pieces like buttons, alerts, cards.

// Component file: resources/views/components/alert.blade.php
<div class="alert alert-{{ $type }}">
  {{ $slot }}
</div>
// Usage
<x-alert type="danger">
  Something went wrong!
</x-alert>

22. Difference between @include, @extends, @component

  • @include – Include a view file.
  • @extends – Extend a layout from a parent Blade file.
  • @component – Use complex components with slot sections.
@extends('layouts.app')

@section('content')
  @include('partials.header')
@endsection

23. How to build a RESTful API in Laravel?

Laravel makes it easy to build REST APIs using apiResource.

php artisan make:controller ProductController --api
Route::apiResource('products', ProductController::class);
// Controller Method
public function index()
{
  return Product::all();
}

24. Difference between apiResource() and resource()

  • resource() – Includes web routes (HTML + forms)
  • apiResource() – Only includes routes for JSON API (GET, POST, PUT, DELETE)

25. Handling API validation errors

public function store(Request $request)
{
  $validated = $request->validate([
    'name' => 'required|string',
    'price' => 'required|numeric'
  ]);

  // Validation passes
  return Product::create($validated);
}

If validation fails, Laravel automatically returns:

{
  "message": "The given data was invalid.",
  "errors": {
    "name": ["The name field is required."]
  }
}

26. Differences in Laravel Caching Drivers

  • File: Stores cache as files (default).
  • Database: Stores cache records in DB table.
  • Redis: Fast, in-memory store, great for high-scale apps.
Cache::put('key', 'value', now()->addMinutes(10));

27. What is the use of config:cache, route:cache, view:cache?

  • config:cache – Speeds up config loading.
  • route:cache – Speeds up routing resolution.
  • view:cache – Compiles Blade views ahead of time.
php artisan config:cache
php artisan route:cache
php artisan view:cache

28. How to use Laravel Broadcasting with Pusher?

  1. Install Pusher SDK: composer require pusher/pusher-php-server
  2. Update broadcasting.php config.
  3. Create event with implements ShouldBroadcast.
broadcast(new MessageSent($user, $message));
Echo.channel('chat')
  .listen('MessageSent', (e) => {
    console.log(e.message);
  });

29. Difference between public and private channels in Broadcasting

  • Public channel: Anyone can listen, no auth required.
  • Private channel: Authenticated and authorized users only.
Broadcast::channel('orders.{orderId}', function ($user, $orderId) {
  return $user->id === Order::find($orderId)->user_id;
});

30. How does Laravel protect against CSRF, XSS, and SQL Injection?

  • CSRF: Laravel includes @csrf tokens in forms and verifies requests via middleware.
  • XSS: Blade escapes all variables using {{ $var }}.
  • SQL Injection: Eloquent and Query Builder use parameter binding.
// CSRF Token
<form method="POST">
  @csrf
  <input name="email">
</form>

// SQL Safe
User::where('email', $email)->first();
Laravel Deep Interview Questions (Q30–Q37)

Laravel Advanced Interview Questions and Deep Explanations (Q30 – Q37)

30. How does Laravel protect against CSRF, XSS, and SQL Injection?

CSRF (Cross-Site Request Forgery): Laravel includes a CSRF token in each form using @csrf. Laravel checks the token on submission and blocks mismatches.

Example:
<form method="POST" action="/submit">
@csrf
<input type="text" name="name">
</form>

XSS (Cross-Site Scripting): Laravel escapes HTML using Blade by default with {{ }}.

Safe: {{ $user->name }}
Unsafe: {!! $user->name !!} (Only use when you trust the data)

SQL Injection: Laravel uses Eloquent and prepared statements under the hood, automatically binding parameters safely.

$user = DB::table('users')->where('email', $email)->first();

31. Difference between validate(), request()->validate() and FormRequest?

  • validate() is a helper method inside controllers that validates incoming requests.
  • request()->validate() is used directly on the request object.
  • FormRequest is a custom request class to encapsulate validation logic cleanly.
Inline (validate):
public function store(Request $request) {
    $request->validate([
      'name' => 'required|min:3',
    ]);
}
FormRequest:
// php artisan make:request StoreUserRequest

public function rules() {
  return ['name' => 'required|min:3'];
}

// In controller:
public function store(StoreUserRequest $request) {
  // Validated automatically
}

32. How do you upgrade a Laravel project from version 8 to 10?

Upgrading Laravel requires step-by-step changes based on the Laravel Upgrade Guide.

  1. Update composer.json to target Laravel 10.
  2. Run composer update.
  3. Review changes to config files, deprecations, removed features.
  4. Refactor old code (e.g., route closures, outdated helpers).
"require": {
  "laravel/framework": "^10.0"
}
Use Laravel Shift (https://laravelshift.com) to automate upgrade process safely.

33. What issues might occur when moving Laravel from localhost to production?

  • Wrong environment variables (.env values need updates).
  • Missing storage links – run: php artisan storage:link
  • Incorrect file/folder permissions (especially storage and bootstrap/cache).
  • Database connection issues (hostnames, ports, credentials).
  • Forgot to run php artisan migrate or php artisan config:cache.
Always disable debug in production:
APP_DEBUG=false

34. Explain the Service Container with example.

The Service Container is Laravel’s powerful dependency injection system that resolves classes and interfaces automatically.

// Binding a service
App::bind('MyService', function() {
  return new \App\Services\MyService();
});

// Resolving
$service = App::make('MyService');

Automatic Injection:

public function __construct(MyService $service) {
  $this->service = $service;
}
Think of the Service Container as Laravel’s internal “object manager” that delivers objects when needed.

35. Difference between Contracts and Facades?

Contract: An interface that defines behavior. Promotes loose coupling and testability.

Facade: A static interface to classes in the service container. Easier to use, but tightly coupled.

Facade: Cache::put('key', 'value');
Contract:
use Illuminate\Contracts\Cache\Repository as Cache;

public function __construct(Cache $cache) {
  $this->cache = $cache;
}

36. What is the difference between Singleton and Binding in Laravel?

Binding: Laravel creates a new instance every time.

Singleton: Laravel reuses the same instance once it's created.

// Binding
App::bind('App\Services\PaymentService', function() {
  return new PaymentService();
});

// Singleton
App::singleton('App\Services\PaymentService', function() {
  return new PaymentService();
});
Use Singleton when your service holds state or needs to be reused (like caching service).

37. What is a Macro in Laravel? How do you use it?

Macros let you extend Laravel classes with custom methods (e.g., Collections, Str, Response).

// Register macro
use Illuminate\Support\Str;

Str::macro('welcome', function($name) {
  return "Welcome, {$name}!";
});

// Usage
echo Str::welcome('Hekima'); // Welcome, Hekima!
You can define your own helper-style methods globally using macros. Ideal for reusable logic.

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1.1::