imbayago imbayago - 6 months ago 49
JSON Question

Laravel search database table for partial match from query

I would like to write a search query that uses a supplied phrase to search a table and return the first value that matches any part of the phrase. Like using

str_contains()
or
starts_with()
to use to match.

The query i have needs to match the entire value otherwise it will always return null.

This is to check if an address exists in a database table.

$addressvalidation = CheckAddress::where('address', '=', $fulladdress)->value('address');


$fulladdress
is the partial address like
1 Infinite Loop Cupertino
that i want to use to search in the database for a match.

CheckAddress
is the query model for the table.

address
is the column name in the table.

The problem is that i can't use
str_contains()
or
starts_with()
to query the database with the partial phrase. The query gets a hit if i match the entire value like
1 Infinite Loop Cupertino, CA 95014

Answer

Try this:

$addressvalidation = CheckAddress::where('address', 'like', "%{$fulladdress}%")->value('address');

Also, checkout the documentation for where statements: https://laravel.com/docs/5.2/queries#where-clauses