ElkunCoding

Searching Records in Laravel

In Laravel, you can use the where method on a query builder instance to search records based on specific criteria. Here is an example of how you could use it to search for records containing a given search term in the title column of a posts table:

$searchTerm = request('search_term');

$posts = DB::table('posts')
            ->where('title', 'like', "%{$searchTerm}%")
            ->get();
            
// ->where('title','LIKE','%'.$searchTerm."%")->get();   // you can also use this one

This will return a collection of all posts with a title that contains the search term. You can also use the orWhere method to specify additional search criteria, or use other operators like =, <, >, etc. depending on your needs.

You can then pass the $posts variable to your view and display the search results to the user.

How to Search Records Between Related Tables in Laravel

To search records between two tables in Laravel, you can use the whereHas method on the query builder. The whereHas method allows you to specify a relationship constraint on the query:

$users = DB::table('users')
            ->whereHas('orders', function($query) {
                $query->where('total', '>', 100);
            })
            ->get();

In this example, the users table is being queried, and the whereHas method is being used to constrain the results to only those users who have at least one order with a total greater than 100.

You can also use join and where to achieve the same result:

$users = DB::table('users')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->where('orders.total', '>', 100)
            ->get();

This will return all users who have at least one order with a total greater than 100.

You can also use Eloquent relationships to search between two tables. For example, if the User model has an orders relationship defined, you can use the whereHas method on the User model to search for users who have at least one order with a total greater than 100:

$users = User::whereHas('orders', function($query) {
                $query->where('total', '>', 100);
            })
            ->get();

Here’s another sample code:

$tickets = Ticket::join('users', 'tickets.user_id', '=', 'users.id')
        ->where('tickets.id', 'like',"%{$search_term}%")
        ->orWhere('users.username','like',"%{$search_term}%")
        ->orWhere('tickets.title', 'like',"%{$search_term}%")
        ->orWhere('tickets.status', 'like',"%{$search_term}%")
        ->orWhere('tickets.ticket_priority', 'like',"%{$search_term}%")
        ->orderBy('tickets.created_at', 'DESC')
        ->with('user')
        ->get(); 

Leave a Comment

Your email address will not be published. Required fields are marked *