Support the ongoing development of Laravel.io →
posted 8 years ago
Database

I want to run various string functions over the data returned from a database query before I send it to the view. Basic stuff like str_replace().

Now maybe there's a good way to setup Accessors on my model and somehow use the model on the landing page but I thought I would go a different route and just do this one query manually outside of the model.

So I have a view provider that successfully gets my data into the view. It looks like this:

    class ViewLandingProvider extends ServiceProvider {
       public function boot() {
        // process when featured homepage element is present...
		View::composer('mybladetemplate', function ($view){
			
			$featuredProperties = DB::table('properties')
				->where([
					['featured_property', '=', '1'],
					['supplier_id', '=', 123],
				])
                ->orderBy('prop_id', 'desc')
				->limit(6)
                ->get();

                // run str_replace!
                $featuredProperties->each(function($property){
                    $property->prop_url=str_replace("http://domain.com/","http://www.domain.com/",$property->prop_url);
                });
			
                View::share('featuredProperties', $featuredProperties);
            });
        }
    }

this then loops within a view and it all works nicely

     @if(isset($featuredProperties))
         @foreach ($featuredProperties as $property)
             <li>
                 <a title="{{ $property->prop_name }}" href="{{ $property->prop_url }}"></a>
             </li>           
        @endforeach
    @endif

As you can see in the example above, I have str_replace() running over the data collection using ->each() and that's working to let me do a simple string replacement that I need to undertake.

Being Laravel though, I'm sure there's some magic that could be pulled here to do this more intelligently.

So is there a way in the actual database request code that I can specify that a certain column to be returned should automatically have a function run over it ?

Just to clarify, I want to make these changes in the provider php rather than the view file and I want to do this outside of a model with Accessors.

Last updated 2 years ago.
0

what you need is a "presenter" pattern in your code

0

Sign in to participate in this thread!

Eventy

Your banner here too?

arkid arkid Joined 23 Oct 2016

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.