masterhunter
masterhunter

Reputation: 559

Remove spaces before getting the result in laravel elequent

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

Answers (4)

Abd Abughazaleh
Abd Abughazaleh

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

omitobi
omitobi

Reputation: 7334

Well I would say:

  1. 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.

  2. 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

masterhunter
masterhunter

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

Yusuf Eka Sayogana
Yusuf Eka Sayogana

Reputation: 401

Try using whereRaw:

$user = User::whereRaw("name REGEXP 'your_regex'")->first();

Upvotes: 0

Related Questions