How To Perform A Search Query In Laravel 11

In Laravel 11, Eloquent provides a powerful ORM (Object-Relational Mapping) for interacting with your database tables. Let’s say we have a User model and we want to perform a search query to retrieve users based on certain criteria. Here’s an example of how to do it:

Assuming we have a users table with columns id, name, email, and created_at, and corresponding fields in our User model, we can construct a search query like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Search users based on name and email.
     *
     * @param string|null $name
     * @param string|null $email
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function searchUsers($name = null, $email = null)
    {
        // Start with a base query
        $query = self::query();

        // If a name is provided, add a where clause to filter by name
        if ($name) {
            $query->where('name', 'LIKE', "%{$name}%");
        }

        // If an email is provided, add a where clause to filter by email
        if ($email) {
            $query->where('email', 'LIKE', "%{$email}%");
        }

        // Execute the query and return the result
        return $query->get();
    }
}

Now, in your controller or wherever you want to use this search functionality, you can call the searchUsers method with the desired parameters:

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    /**
     * Search users based on name and email.
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function search(Request $request)
    {
        // Retrieve search parameters from the request
        $name = $request->input('name');
        $email = $request->input('email');

        // Call the searchUsers method on the User model
        $users = (new User)->searchUsers($name, $email);

        // Return the result, for example, as JSON
        return response()->json($users);
    }
}

In this example, we’ve created a method searchUsers in the User model that accepts parameters for name and email. It constructs a query based on the provided parameters and returns the result. Then, in the controller, we call this method based on the request parameters and return the result, typically as JSON.

For more posts like this click here

Leave a Reply