Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilbertozioma/ec9f1f1de9b4e152f03e2b0b7f2926ce to your computer and use it in GitHub Desktop.
Save gilbertozioma/ec9f1f1de9b4e152f03e2b0b7f2926ce to your computer and use it in GitHub Desktop.
Technical Interviews and Coding Tasks for PHP/Laravel Backend Developer role

These are the tasks you might encounter in your PHP/Laravel job interviews:

  1. Coding exercises: These may involve solving programming problems using PHP or other relevant languages, implementing algorithms, or working with data structures.

  2. API design and implementation: You might be asked to design and implement APIs to meet specific requirements or integrate with existing systems.

  3. Database queries: You could be given tasks that involve writing SQL queries to retrieve or manipulate data in a database.

  4. Framework-specific tasks: You may have tasks to work with Laravel.

  5. Code review: You might be asked to review code snippets and identify potential issues or suggest improvements.

  6. Problem-solving scenarios: You could face real-world scenarios related to product development, where you need to come up with solutions to complex challenges.

  7. Security considerations: Questions may involve identifying and implementing secure programming practices to protect against potential vulnerabilities.

  8. Automated testing: Tasks might focus on writing unit tests or setting up automated testing methods.

The TASKS AND SOLUTIONS:

1. Coding Exercises (PHP)

Task 1: Write a function that takes an array of integers as input and returns the sum of all even numbers in the array.

function sumEvenNumbers(array $numbers): int {
    $sum = 0;
    foreach ($numbers as $num) {
        if ($num % 2 === 0) {
            $sum += $num;
        }
    }
    return $sum;
}

A numerical palindrome is a number that reads the same backwards and forwards. An example of numerical palindromes: 101 555 20102.

Task 2: Implement a function to check if a given string is a palindrome (reads the same backward as forward).

function isPalindrome(string $str): bool {
    $reversed = strrev($str);
    return $str === $reversed;
}

// OR
 

// Create the function findNumericalPalindrome
// which takes two positive integers as its argument and returns the numerical palindromes
// as an array of $n numerical palindromes that come after $num, including $num.

// Define a function to find numerical palindromes
function findNumericalPalindrome($num, $n)
{
    // Initialize an array to store the palindromes
    $palindromes = array(); 

    // Loop until the desired number of palindromes is found
    while (count($palindromes) < $n) {
        // Check if the current number is a palindrome (reads the same forwards and backwards)
        if ($num == strrev($num)) {
            // If yes, add it to the list of palindromes
            $palindromes[] = $num; 
        }
        // Increment the number to check the next one
        $num++; 
    }

    // Return the list of palindromes
    return $palindromes; 
}

    // Set the number of palindromes to find
    $n = 10; 
    // Set the starting number
    $num = 100; 
    // Call the function to find palindromes
    $palindromes = findNumericalPalindrome($num, $n); 
    // print_r ($palindromes);

    // Loop through each palindrome and print it
    foreach ($palindromes as $palindrome) {
        // Print each palindrome and move to the next line
        echo $palindrome . PHP_EOL .'<br>'; 
    }

Task 3: Create a function to find the second-largest element in an array of integers.

function findSecondLargest(array $numbers): int {
    rsort($numbers);
    return $numbers[1];
}

2. API Design and Implementation(PHP)

Task 1: Design an API endpoint to retrieve a user's profile information by their ID.

Solution:

The API endpoint

GET /api/users/{user_id}

Response1 (JSON):

{
  "user_id": 1,
  "name": "Gilbert Ozioma",
  "email": "gilbertozioma0@gmail.com",
  "bio": "Backend Web Developer",
  "url": "https://about.me/gilbertozioma",
  "created_at": "2023-08-07T12:34:56Z"
}

Pseudo-code implementation of the API endpoint:

<?php

// Function to retrieve user profile by ID
function get_user_profile($user_id) {

    // Fetch user profile from the database or any other data source
    $user_profile = getUserProfileFromDatabase($user_id);
    return $user_profile;
}

// Check if the request method is GET and the user_id parameter exists
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['user_id'])) {
    $user_id = $_GET['user_id'];
    $user_profile = get_user_profile($user_id);
    
    // Set the appropriate content type and status code
    header('Content-Type: application/json');
    if ($user_profile) {
        http_response_code(200);
        echo json_encode($user_profile);
    } else {
        http_response_code(404);
        echo json_encode(array("error" => "User not found"));
    }
} else {
    // Return an error for unsupported requests
    http_response_code(405);
    echo json_encode(array("error" => "Method Not Allowed"));
}
?>

Task 2: Implement an API endpoint to create a new post with title and content.

Solution:

The API endpoint

POST /api/posts

Request (JSON):

{
  "title": "New Post Title",
  "content": "This is the content of the new post."
}

Response2 (JSON):

{
  "status": "success",
  "message": "Post created successfully",
  "post_id": 12345
}
<?php

// Function to create a new post
function create_new_post($data) {

    // Generate a unique post ID
    $post_id = generateUniqueId();
    
    // Save the post to the database with the provided title and content
    savePostToDatabase($post_id, $data['title'], $data['content']);
    
    return $post_id;
}

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Get the JSON data from the request body
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Ensure that the required fields are provided (title and content)
    if (isset($data['title']) && isset($data['content'])) {
        // Create the new post
        $post_id = create_new_post($data);
        
        // Set the appropriate content type and status code
        header('Content-Type: application/json');
        http_response_code(201);
        
        // Respond with the success message and the new post's ID
        echo json_encode(array(
            "status" => "success",
            "message" => "Post created successfully",
            "post_id" => $post_id
        ));
    } else {
        // Return an error if title and content are not provided
        http_response_code(400);
        echo json_encode(array("error" => "Title and content are required"));
    }
} else {
    // Return an error for unsupported requests
    http_response_code(405);
    echo json_encode(array("error" => "Method Not Allowed"));
}

3. Database Queries(PHP)

Task 1: Write a SQL query to retrieve all users from the "users" table with their names and email addresses.

Solution:

SELECT name, email FROM users;

Task 2: Write a SQL query to calculate the average age of all users in the "users" table.

Solution:

SELECT AVG(age) AS average_age FROM users;

Task 3: Write a SQL query to find the top 5 products with the highest sales in the "sales" table.

Solution:

SELECT product_name, SUM(quantity) AS total_sales
FROM sales
GROUP BY product_name
ORDER BY total_sales DESC
LIMIT 5;

5. API Design and Implementation (Laravel)

Task 1: Design an API endpoint to retrieve a list of all products with their details from the "products" table.

Solution:

// Route definition using Laravel's routing
Route::get('/api/products', 'ProductController@index');

// Controller method to handle the request
public function index() {
    $products = Product::all();
    return response()->json($products);
}

Task 2: Implement an API endpoint to create a new order for a customer with multiple products.

Solution:

// Route definition using Laravel's routing
Route::post('/api/orders', 'OrderController@store');

// Controller method to handle the request
public function store(Request $request) {
    $validatedData = $request->validate([
        'customer_id' => 'required|integer',
        'products' => 'required|array',
    ]);

    // Create the order and store it in the database
    $order = Order::create([
        'customer_id' => $validatedData['customer_id'],
    ]);

    // Attach products to the order
    $order->products()->attach($validatedData['products']);

    return response()->json(['message' => 'Order created successfully'], 201);
}

Task 3: Design an API endpoint to delete a specific user from the "users" table.

Solution:

// Route definition using Laravel's routing
Route::delete('/api/users/{id}', 'UserController@destroy');

// Controller method to handle the request
public function destroy($id) {
    $user = User::find($id);

    if (!$user) {
        return response()->json(['message' => 'User not found'], 404);
    }

    // Delete the user from the database
    $user->delete();

    return response()->json(['message' => 'User deleted successfully'], 200);
}

6. Automated Testing (Laravel)

Task 1: Write a PHPUnit test to check if the "getAverageRating" method of the "Product" model correctly calculates the average rating of a product based on its reviews.

Solution:

use Tests\TestCase;
use App\Models\Product;
use App\Models\Review;

class ProductTest extends TestCase
{
    public function testGetAverageRating()
    {
        $product = Product::factory()->create();

        // Create reviews for the product
        Review::factory()->create(['product_id' => $product->id, 'rating' => 5]);
        Review::factory()->create(['product_id' => $product->id, 'rating' => 4]);

        // Calculate the expected average rating (4.5 in this case)
        $expectedAverage = (5 + 4) / 2;

        // Test the getAverageRating method
        $this->assertEquals($expectedAverage, $product->getAverageRating());
    }
}

Task 2: Write a Dusk test to check if the "Add to Cart" button is functional on the product details page.

Solution:

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class ProductTest extends DuskTestCase
{
    public function testAddToCartButton()
    {
        $this->browse(function (Browser $browser) {
            // Visit the product details page
            $browser->visit('/products/1');

            // Click the "Add to Cart" button
            $browser->press('Add to Cart');

            // Check if the product has been added to the cart
            $browser->assertSee('Product added to cart successfully');
        });
    }
}

Task 3: Write a test to check if the user receives a 404 response when trying to access a non-existent product page.

Solution:

use Tests\TestCase;

class ProductTest extends TestCase
{
    public function testNonExistentProductPage()
    {
        $response = $this->get('/products/999');

        // Assert that the response has a 404 status code
        $response->assertStatus(404);
    }
}

7. Virtual Infrastructure Automation (Laravel)

Task 1: Set up a Laravel Forge environment and provision a new server for the application.

Solution: Laravel Forge is a tool for managing servers and deployments. The exact steps would depend on your specific server setup and configurations.

Task 2: Automate the deployment process using a deployment script or a CI/CD pipeline.

Solution: You can use tools like Laravel Envoyer or Jenkins to create a CI/CD pipeline for automated deployments.

Task 3: Implement a scheduled task using Laravel's task scheduling to perform routine maintenance tasks, like clearing cache or generating reports.

Solution: Define the scheduled task in the app/Console/Kernel.php file:

protected function schedule(Schedule $schedule)
{
    // Clear cache every day at midnight
    $schedule->command('cache:clear')->dailyAt('00:00');

    // Generate reports every Sunday at 3 AM
    $schedule->command('generate:reports')->weeklyOn(0, '03:00');
}

8. Database Schemas (Laravel)

Task 1: Design a database schema for a simple e-commerce system with tables for products, orders, customers, and reviews.

Solution:

Products table migration

// products table migration
Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->decimal('price', 8, 2);
    $table->timestamps();
});

Orders table migration

// orders table migration
Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('customer_id');
    $table->timestamps();

    $table->foreign('customer_id')->references('id')->on('customers');
});

Customers table migration

// customers table migration
Schema::create('customers', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamps();
});

Reviews table migration

// reviews table migration
Schema::create('reviews', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('product_id');
    $table->text('comment');
    $table->unsignedTinyInteger('rating');
    $table->timestamps();

    $table->foreign('product_id')->references('id')->on('products');
});

Task 2: Create a database migration to add a "quantity" column to the "products" table.

Solution: Create a new migration file using the 'artisan' command:

php artisan make:migration add_quantity_to_products_table --table=products

Update the new migration file with the following code:

public function up()
{
    Schema::table('products', function (Blueprint $table) {
        $table->unsignedInteger('quantity')->default(0);
    });
}

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

Task 3: Write a database seed to populate the "products" table with sample data.

Solution: Create a new seeder file using the 'artisan' command:

php artisan make:seeder ProductSeeder

Then, update the new seeder file with the following code:

use Illuminate\Database\Seeder;
use App\Models\Product;

class ProductSeeder extends Seeder
{
    public function run()
    {
        Product::create(['name' => 'Product 1', 'price' => 10.99, 'quantity' => 100]);
        Product::create(['name' => 'Product 2', 'price' => 19.99, 'quantity' => 50]);
        // Add more products as needed
    }
}

Run the seed using the db:seed command:

php artisan db:seed --class=ProductSeeder

THE END

Star this gist if you found this helpful.

You're Welcome. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment