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

elbgoods's avatar

how to use like operator with '%'-Wildcard in where function of Collection in Laravel 5.3

Hi, I want to make a query like "SELECT * FROM bookings' WHERE bill_of_delivery LIKE '123%'; " using Eloquent. I try to implememt it using the code below.

$bookings = BookingOverview::all();
// ...
$bookings = $bookings->where('bill_of_delivery', 'like', $request->get('bill_of_delivery') . '%');
// ...

When I tested it I got no results. It seems that Eloquent escapes the %-Wildcard. How can I unescape this Operator?

0 likes
4 replies
tykus's avatar

This returns a Collection instance:

$bookings = BookingOverview::all();

so you are no longer dealing with Eloquent (or SQL) when you get to the second statement

Do this instead:

$bookings = BookingOverview::where('bill_of_delivery', 'like', $request->get('bill_of_delivery') . '%')->get();
1 like
elbgoods's avatar

thanks for helping but the problem is that this field isn't in the used table. This field is in a joined table. I access this field via the model using follwing.

public function getBillOfDeliveryAttribute(){
        return $this->booking->bill_of_delivery;
    }

When I use BookingOverview::where I got an error that 'bill_of_delivery' is missing in my table.

tykus's avatar

@elbgoods that wasn't at all clear from your original post...

What is the relationship between Booking and BookingOverview?

elbgoods's avatar

relation is one Booking has meny BookingOverviews.

I just now solved it using query scopes. I have following scopes in my BookingOverview-Model

public function scopeBeginsWith($query, $field, $input)
    {
        if(!$input) return $query;
        return $query->where($field, 'like', $input . '%');
    }

    public function scopeWithBookings($query)
    {
        return $query->join('bookings', 'bookings.id', '=', 'bookings_oberview.booking_id');
    }

and use now

$bookings = BookingOverview::withBookings()
            ->beginsWith('bill_of_delivery', $request->get('bill_of_delivery', ''))
            ->get();

to get what I want.

Please or to participate in this conversation.