How to Create a Mock Controller with User Data in Laravel

 


Working on a Laravel project and need sample user data for testing purposes? Setting up a mock controller with some realistic user data can be a great approach, especially if you're prototyping or want to focus on front-end features without setting up a database. In this article, we’ll walk through creating a UsersController in Laravel that provides mock user data and implements CRUD operations for demonstration and testing.

1. Setting Up the Controller

To begin, create a new controller in Laravel named UsersController. This will serve as our mock API endpoint for managing user data. We’ll store our user data in an array, simulating a database table.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class UsersController extends Controller
{
    public $users;

    function __construct() {
        // Sample users data
        $this->users = [
            [
                'id' => 1,
                'name' => 'Emma Smith',
                'email' => 'smith@kpmg.com',
                'position' => 'Art Director',
                'role' => 'Administrator',
                'last_login' => 'Yesterday',
                'two_steps' => false,
                'joined_day' => "10 Nov 2022, 9:23 pm",
                'online' => false
            ],
            // Additional sample users here
        ];
    }
}

This constructor method initializes an array of user data. Each user has attributes like id, name, email, role, and last_login. You can customize these attributes to fit your needs.

2. Fetching Users List with Pagination and Filters

Our next step is to create a method to fetch all users, including pagination and filtering functionality. This helps us simulate a real database where we can retrieve, sort, and filter data.

public function getUsers(Request $request)
{
    $usersCollection = collect($this->users);
    $page = $request->input('page', 1);
    $perPage = $request->input("items_per_page", 10);

    // Search and filter logic here
    // Paginate users
    $paginatedUsers = $this->paginate($usersCollection, $perPage, $page);

    return response(["data" => $paginatedUsers->toArray()], 200);
}

This method retrieves users as a collection and paginates the results. We also implement a helper function paginate() to manually paginate the data.

3. Adding a User

Adding a new user in this mock setup requires validating the input and appending it to our users array. Here’s how:

public function addUser(Request $request)
{
    $data = json_decode($request->getContent(), true);

    $validator = Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255',
        'role' => 'required|string|max:255',
    ]);

    if ($validator->fails()) {
        return response(["errors" => $validator->errors()], 422);
    }

    $data["id"] = count($this->users) + 1;
    $this->users[] = $data;

    return response(["data" => $data], 201);
}

This function adds a new user only if the data is valid, simulating the behavior of a real database-backed POST request.

4. Updating User Data

Updating a user’s information is similar to adding a new user, but here we first locate the user by ID, then update the existing array entry:

public function updateUser(Request $request, $id)
{
    $data = json_decode($request->getContent(), true);

    $validator = Validator::make($data, [
        'name' => 'required|string|max:255',
        'email' => 'required|string|email|max:255',
        'role' => 'required|string|max:255',
    ]);

    if ($validator->fails()) {
        return response(["errors" => $validator->errors()], 422);
    }

    $user = collect($this->users)->firstWhere('id', $id);

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

    $user = array_merge($user, $data);
    return response(["data" => $user], 200);
}


5. Deleting a User

Deleting a user is as straightforward as removing the user by ID from the array. Here’s a simple deleteUser function:

<?php
public function deleteUser($id)
{
    $key = array_search($id, array_column($this->users, 'id'));

    if ($key === false) {
        return response(["message" => "User not found"], 404);
    }

    unset($this->users[$key]);
    return response(null, 204);
}


6. Creating the Paginate Function

Since we’re working with an array instead of a database, we need a custom paginator. Here’s a function to handle manual pagination:

<?php
public function paginate($items, $perPage = 10, $page = null)
{
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage)->values(), $items->count(), $perPage, $page);
}


The paginate function lets us handle pagination just like we would with Eloquent collections.

Wrapping Up

With this setup, you now have a fully functional mock user controller in Laravel! This mock controller can be extended with additional endpoints or adapted to handle more complex mock data requirements. Whether you’re building a front-end prototype or testing Laravel API responses, this approach can save you time and simplify your development process.

You can get the complete code here on Github

Previous Post Next Post

نموذج الاتصال