Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Wakanda's avatar
Level 10

Derive a Laravel search query from a provided test.

Hi, I am working on a project that has some tests implemented and i would want to derive a search query based on the provided test case

Test

   public function test_index_returns_based_on_name_search()
    {
        Company::factory()->count(20)->create();
        Company::factory()->create(['name' => 'Test Name']);

        $result = $this->getJson(route("companies.index") . '?name=Test');


        $result->assertStatus(Response::HTTP_OK);
        $result->assertJsonCount(1, 'data');
        $result->assertJsonFragment(['total' => 1]);
        $result->assertJsonFragment(['name' => 'Test Name']);
    }

My controller

public function index(Request $request)
    {
        $companies = Company::query()
            ->with('ratings')
            ->paginate($request->get('per_page', 10));

        return new CompanyCollection($companies);
    }

a company has many ratings

Company model

so basically i need update the controller to match the test case

0 likes
5 replies
Wakanda's avatar
Level 10

For more clarity i need to update the Company::query() in the controller to do the search

Energy G's avatar

you could have a query scope in your model

Wakanda's avatar
Wakanda
OP
Best Answer
Level 10

found a solution for test test_index_returns_based_on_name_search

$companies = Company::where('name', 'like', '%' .$name . '%')
            ->with('ratings')
            ->paginate($request->get('per_page', 10));

Please or to participate in this conversation.