Kenny Hietbrink Kenny Hietbrink - 1 year ago 190
PHP Question

Laravel 5: Replace string in query results (Eloquent ORM)

Is it possible to return all columns from a table, but if a string (value) contains a specific word, remove that word?

For example, I have a table like this:


-------------------------------------------------
| id | article_desc | article_link | active |
|----|------------------|----------------|--------|
| 1 | Hello, world! | http://test.co | 0 |
| 2 | ReplaceWord Test | http://null.org| 1 |
-------------------------------------------------


"ReplaceWord" should be replaced to "" (nothing). So article_desc of ID 2 should return "Test".

Is there any way to do this in Laravel (Eloquent) without using a foreach or something? Is there any built-in function?

This is my controller where I am getting this data.

return Article::where('active', 1)->orderBy('create_date', 'desc')->get();


Thanks!

Answer Source

Eloquent queries return a Laravel collection, so you can use the map function to loop over the results and replace the strings.

return Article::where('active', 1)
    ->orderBy('create_date', 'desc')
    ->get()
    ->map(function ($article) {
        $article->article_desc = str_replace('ReplaceWord', '', $article->article_desc);

        return $article;
    });

If you want the value to be replaced for every query, you can create an accessor for this field on your Article model.

public function getArticleDescAttribute($value)
{
    return str_replace('ReplaceWord', '', $value)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download