Vijayanand Premnath
Vijayanand Premnath

Reputation: 3615

Laravel get all the values of a column beginning with a number

I have a model called "Image" and a table called "images". The table has a column for the "id" and another for the "name". I need to fetch only the rows with the name beginning with a number.

I need to fetch are called something like

16783521_facebook.png

While the others are something like...

twiter.png

Upvotes: 0

Views: 227

Answers (4)

Matt McDonald
Matt McDonald

Reputation: 5050

Try this:

Image::whereRaw("name REGEXP '^[0-9]'") -> get();

If it's something you're going to use in more than 1 place, consider moving it to a scope.

In your image model define something like:

public function scopeNumeric($query)
{
    return $query -> whereRaw("name REGEXP '^[0-9]'");
}

Then you can just use:

Image::numeric() -> get();

Upvotes: 1

Vijayanand Premnath
Vijayanand Premnath

Reputation: 3615

Filter the images after the query using one of the collection methods. Like below solved me.

$onlyNumeric = $photos->filter(function ($value, $key) {
return is_numeric(substr($value, 0, 1));
});

Upvotes: 0

Joel Hinz
Joel Hinz

Reputation: 25384

Laravel doesn't have that built-in, so you'll have to make do with raw queries. In its base form:

$results = SomeModel::whereRaw("some_column REGEXP '^[0-9]'")->get();

You can modify this as usual with selects, other limitations, etc. as you require.

Upvotes: 1

Ashly
Ashly

Reputation: 521

I dont know much about laravel, but this plain query will help -

SELECT * FROM mytable WHERE mycolumn REGEXP '^[0-9]+$' or
SELECT * FROM myTable WHERE col1 REGEXP '[0-9]+';

Upvotes: 1

Related Questions