Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 

Repository files navigation

Advanced Laravel PHP Technical Skills Evaluation Questions

Table of Contents

  1. Migration-Related Questions
  2. API Controller-Related Questions
  3. Other Advanced Laravel Questions

Migration-Related Questions

Question 1: Troubleshooting Failed Migrations

You're working on a Laravel application and need to add a new column to an existing table. You've created the following migration:

<?php

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

class AddStatusToOrdersTable extends Migration
{
    public function up()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->enum('status', ['pending', 'processing', 'completed', 'cancelled']);
        });
    }

    public function down()
    {
        Schema::table('orders', function (Blueprint $table) {
            $table->dropColumn('status');
        });
    }
}

When you run php artisan migrate, you get the following error:

SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'status'

Identify the issue and provide a solution to fix this migration. What Laravel migration command would you use to check the status of migrations, and how would you modify this migration to make it work correctly?


Question 2: Handling Database Schema Changes in Production

You need to modify an existing column in a production database from VARCHAR(50) to VARCHAR(100) and rename it from user_name to full_name. The table contains thousands of records with existing data that must be preserved.

Write a migration that safely performs this change, ensuring no data is lost. Include both the up() and down() methods. Additionally, explain what precautions you would take when deploying this migration to production.


Question 3: Resolving Migration Dependency Issues

You have two migrations:

  1. 2023_01_01_000000_create_categories_table.php - Creates the categories table
  2. 2023_01_01_000001_create_products_table.php - Creates the products table with a foreign key to categories

The products migration has already been run in production, but you discover that the categories migration was accidentally skipped, causing database integrity issues.

How would you resolve this situation without losing any data? Write the commands and explain your approach to fix this issue. What Laravel migration features would you use to prevent similar issues in the future?


API Controller-Related Questions

Question 4: Debugging API Authentication Issues

You're working on a Laravel API that uses Laravel Passport for authentication. Users are reporting that they occasionally receive 401 Unauthorized errors even with valid tokens. The following is the controller method handling the request:

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    public function getProfile(Request $request)
    {
        $user = $request->user();
        
        return response()->json([
            'success' => true,
            'data' => $user
        ]);
    }
}

The route is defined in routes/api.php as:

Route::get('/user/profile', [App\Http\Controllers\API\UserController::class, 'getProfile']);

Identify potential issues that could cause intermittent authentication failures and explain how you would debug and fix them. Include considerations for token expiration, middleware configuration, and any other relevant factors.


Question 5: Optimizing API Response Performance

You have an API endpoint that returns a list of products with their categories, tags, and reviews. The endpoint is experiencing slow response times, especially as the number of products grows. Here's the current controller method:

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $products = Product::all();
        
        $result = [];
        foreach ($products as $product) {
            $result[] = [
                'id' => $product->id,
                'name' => $product->name,
                'price' => $product->price,
                'description' => $product->description,
                'category' => $product->category->name,
                'tags' => $product->tags->pluck('name'),
                'reviews' => $product->reviews->map(function($review) {
                    return [
                        'rating' => $review->rating,
                        'comment' => $review->comment,
                        'user' => $review->user->name
                    ];
                })
            ];
        }
        
        return response()->json([
            'success' => true,
            'data' => $result
        ]);
    }
}

Identify the performance issues in this code and refactor it to improve response times. Include considerations for database queries, resource transformations, pagination, and caching. Explain the benefits of your optimized solution.


Question 6: Implementing Rate Limiting for API Endpoints

You need to implement rate limiting for your Laravel API to prevent abuse. The requirements are:

  1. Public endpoints should be limited to 60 requests per minute per IP address
  2. Authenticated endpoints should be limited to 120 requests per minute per user
  3. Certain premium users should have higher limits (300 requests per minute)

Write the necessary code to implement these requirements, including:

  1. Middleware configuration
  2. Route group setup
  3. Custom rate limiter definition

Explain how you would handle rate limit exceeded scenarios, including appropriate HTTP status codes and response formats. Also, describe how you would test your rate limiting implementation.


Other Advanced Laravel Questions

Question 7: Service Container and Dependency Injection

You're working on a Laravel application that needs to interact with multiple payment gateways (PayPal, Stripe, etc.). You want to implement a flexible architecture using Laravel's Service Container.

Given the following interface:

<?php

namespace App\Contracts;

interface PaymentGatewayInterface
{
    public function charge(float $amount, array $paymentDetails);
    public function refund(string $transactionId);
}

And two implementations:

<?php

namespace App\Services;

use App\Contracts\PaymentGatewayInterface;

class StripePaymentGateway implements PaymentGatewayInterface
{
    protected $apiKey;
    
    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
    }
    
    public function charge(float $amount, array $paymentDetails)
    {
        // Stripe-specific implementation
    }
    
    public function refund(string $transactionId)
    {
        // Stripe-specific implementation
    }
}

class PayPalPaymentGateway implements PaymentGatewayInterface
{
    protected $clientId;
    protected $clientSecret;
    
    public function __construct(string $clientId, string $clientSecret)
    {
        $this->clientId = $clientId;
        $this->clientSecret = $clientSecret;
    }
    
    public function charge(float $amount, array $paymentDetails)
    {
        // PayPal-specific implementation
    }
    
    public function refund(string $transactionId)
    {
        // PayPal-specific implementation
    }
}

Write the necessary code to:

  1. Register these services in a service provider
  2. Configure the application to use different payment gateways based on configuration
  3. Inject the appropriate payment gateway into a controller

Explain how Laravel's Service Container resolves dependencies and how your implementation leverages this feature.


Question 8: Event Broadcasting and Real-time Updates

You're building a collaborative task management application where users need to see real-time updates when tasks are created, updated, or deleted.

Implement the necessary components to broadcast these events to authenticated users, including:

  1. An event class for task updates
  2. A listener to handle the event
  3. Configuration for broadcasting via WebSockets
  4. Front-end code to listen for and handle the broadcasted events

Explain potential issues that might arise in a production environment and how you would address them.


Question 9: Custom Middleware for Complex Authorization

Your application has a complex permission system where access to resources depends on:

  • User role (admin, manager, staff)
  • Department assignment
  • Resource ownership
  • Time-based restrictions (some resources are only accessible during business hours)

Create a custom middleware that handles these complex authorization rules. Your solution should:

  1. Define the middleware class
  2. Register it in the appropriate location
  3. Implement the logic to check all required conditions
  4. Handle authorization failures appropriately

Explain how you would test this middleware and how it integrates with Laravel's authorization system.


Question 10: Optimizing Eloquent Relationships and Database Queries

You've identified a performance bottleneck in your application related to the following Eloquent query:

$reports = Report::with(['department', 'author', 'comments', 'attachments'])
    ->where('status', 'published')
    ->orderBy('created_at', 'desc')
    ->get();

foreach ($reports as $report) {
    echo $report->title . ' by ' . $report->author->name . ' (' . $report->department->name . ')';
    echo 'Comments: ' . $report->comments->count();
    
    foreach ($report->comments as $comment) {
        echo $comment->author->name . ': ' . $comment->content;
    }
    
    foreach ($report->attachments as $attachment) {
        echo $attachment->filename . ' (' . $attachment->filesize . ' bytes)';
    }
}

Identify the N+1 query problems and other performance issues in this code. Refactor it to optimize database queries while maintaining the same functionality. Explain your optimization strategy and how it improves performance.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors