mardi 25 octobre 2016

formatting results from laravel composer without using a model?

I'm new to Laravel and I'm in the process of building a model for a new website I'm making. So far that's working. There is however a need on the homepage of the website to also show data from the database table used in the model.

I need to run various string functions over the data returned from the database 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();

        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="" href=""></a>
         </li>           
    @endforeach
@endif

But as you can see I haven't got anywhere so far in place to run formatting over the fields returned from the db.

So what's the best way of running a formatting command over all the values of certain columns? Being Laravel I'm sure there's some magic that could be pulled here to run something over the $featuredProperties object that I've returned from the database, but I've no idea what.

Just to clarify, I want to make these changes in the provider php rather than the view file.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire