How to check a string is matching with 2 columns in database - Laravel

Viewed 109

Am working on a scenario, where I want to search for a string value from URL is matching 2 columns from the database. For example.. in my project system, there is customer first_name and last_name is there while entering web URL like website.com/nayanachandran

the word "nayanachandran" has to check from the customer database, with laravel queries like the combination of customer first_name and last_name is equal to the string in request param. currently, I did it in a way like added hi-pen in string eg: nayana-chandran

and while searching I added query in the repository like:

    $publicUrl = explode("-",$this->request->unique_name);
    $coach_details = Customer::where('first_name', $publicUrl['0'])->where('last_name', $publicUrl['1'])->first();

Any help ?

2 Answers

It sounds like you're asking how you can take a concatenated string from the url, nayanachandran, and search for that in your DB as a combination of the columns first_name and last_name.

Assuming that's the case, you can use a combination of whereRaw and CONCAT:

Customer::whereRaw("CONCAT(first_name, last_name) = ?", [$this->request->unique_name])->first();

Alright, so a way to do this would be to:

$publicUrl = explode('-', $this->request->unique_name);
list($firstName, $lastName) = $publicUrl;

Which indeed creates an array from the string delimited by '-', and then simply do a:

Customer::where([['first_name', $firstName],['last_name', $lastName]])->first();

Which will return you the Customer object related to that condition.

However, let me recommend you to use query strings instead, and simply have an address like:

https://address.com/example?first_name=james&last_name=smith

Which would render the explode unnecessary since you could access those values directly from the request object:

Customer::where([['first_name', request()->get('first_name')],['last_name', request()->get('last_name')]])->first();
Related