lamlichus
lamlichus

Reputation: 21

How to do string functions on a db table column?

I am trying to do string replace on entries of a column inside a db table. So far, I have reached till here:

$misa = DB::table('mis')->pluck('name');
for($i=0;;$i++)
{
    $misa[$i] = substr_replace("$misa[$i]","",-3);
}  

The error I am getting is "Undefined offset:443".

P.S. I am not a full-fledged programmer. Only trying to develop a few simple programs for my business. Thank You.

Upvotes: 1

Views: 50

Answers (2)

Luke
Luke

Reputation: 1033

There are a few ways to make this query prettier and FASTER! The beauty of Laravel is that we have the use of both Eloquent for pretty queries and then Collections to manage the data in a user friendly way. So, first lets clean up the query. You can instead use a DB::Raw select and do all of the string replacing in the query itself like so:

$misa = DB::table('mis')->select(DB::raw("REPLACE(name, ':ut' , '') as name"));

Now, we have a collection containing only the name column, and you've removed ':ut' in your specific case and simply replaced it with an empty string all within the MySQL query itself.

Surprise! That's it. No further php manipulation is required making this process much faster (will be noticeable in large data sets - trust me).

Cheers!

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163858

Since it's a collection, use the transform() collection method transform it and avoid this kind of errors. Also, you can just use str_before() method to transform each string:

$misa = DB::table('mis')->pluck('name');
$misa->transform(function($i) {
    return str_before($i, ':ut');
});

Upvotes: 2

Related Questions