Reputation: 559
i want to compare the search result in laravel controller.
When user input the name and search. In my controller it will remove the input spaces and compare data retrieved from database.
Users submitted is John Doe
preg_match_all('/\@([^\s\.]+)/', $request->name, $matches);
Remove spaces become JohnDoe. Then get data with
$user = User::where('name', $name)->first();
And i want remove the name column spaces before comparing the result. For example the data get from database column is John Doe. How to remove the spaces and comparing them.
$user = User::where('John Doe', $matches)->first();
Upvotes: 4
Views: 4355
Reputation: 5525
I did use whereRaw
User::whereRaw("REPLACE('name', ' ', '') = ? ", $request->name)->first();
and also if you want to use OR
you can use: orWhereRaw
orWhereRaw
or whereRaw
used to write SQL functions.
Upvotes: 0
Reputation: 7334
Well I would say:
There is a problem if you are saving a different data to the one you really need. I mean you can easily save JohnDoe and its easy, and also makes life easy.
You can use Raw sql query with whereRaw()
method as such:
User::whereRaw("REPLACE(`name`, ' ', '') = ? ", $name)->first();
The REPLACE()
removes all whitespace and with no space. Find more about mysql REPLACE()
here
Upvotes: 2
Reputation: 559
I found that this methods could be work.
$user = User::where('name','%'.$name.'%')
->orWhere('name','LIKE','%'.preg_replace('/\@([^\s\.]+)/', '', $name).'%')->first();
Upvotes: 0
Reputation: 401
Try using whereRaw
:
$user = User::whereRaw("name REGEXP 'your_regex'")->first();
Upvotes: 0