I need to run various string functions on the data returned from the database before sending them to the view using Laravel 5.3. Basic things like str_replace ().
Now, there may be a good way to configure Accessors on my model and somehow use the model on the landing page, but I thought I would go on a different route and just make this request manually outside 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); }); } }
then it's the loops inside the view and it all works great
@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 above example, I have str_replace () working on a data collector using → each (), and this works to allow me to perform a simple string replacement that I need to take.
Being Laravel, I am sure that there is some kind of magic that could be pulled out here to make it more reasonable.
So, is there a way in the actual code of the database query that I can indicate that a particular column to be returned should automatically run a function on it?
To clarify, I want to make these changes to the provider php, not the view file, and I want to do this outside the model using Accessors.