1

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.

2
  • 2
    What exactly are you trying to achieve? Could you give examples of names you have and what the exact result you want to get? Commented Feb 5, 2018 at 11:09
  • These are product codes like socf:ut, tis:ut. I want to remove :ut from the end of all product codes. Commented Feb 5, 2018 at 11:12

2 Answers 2

2

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');
});
Sign up to request clarification or add additional context in comments.

1 Comment

It worked. Thank you very much. Makes my work so much easier.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.