Ada*_*nes 7 php laravel laravel-5
在使用Laravel 5.3将其发送到视图之前,我需要对从数据库返回的数据运行各种字符串函数.像str_replace()这样的基本内容.
现在也许有一个很好的方法在我的模型上设置Accessors并以某种方式在着陆页上使用该模型,但我想我会走另一条路线,只是在模型之外手动执行这一个查询.
所以我有一个视图提供程序,可以成功地将我的数据导入视图.它看起来像这样:
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);
    });
  }
}
然后在视图中循环,这一切都很好
 @if(isset($featuredProperties))
     @foreach ($featuredProperties as $property)
         <li>
             <a title="{{ $property->prop_name }}" href="{{ $property->prop_url }}"></a>
         </li>           
    @endforeach
@endif
正如您在上面的示例中所看到的,我使用 - > each()在数据集合上运行str_replace(),这样我就可以让我进行一个简单的字符串替换.
虽然是Laravel,但我确信有一些魔法可以被拉到这里以更聪明地做到这一点.
那么在实际的数据库请求代码中是否有一种方法可以指定要返回的某个列应该自动运行一个函数呢?
只是为了澄清,我想在提供者php而不是视图文件中进行这些更改,我想在带有Accessors的模型之外执行此操作.
您可以将选择查询编写为:
$featuredProperties = DB::table('properties')
    ->where([
        ['featured_property', '=', '1'],
        ['supplier_id', '=', 123],
    ])
    ->select('*', DB::raw("replace(prop_url, 'http://domain.com/', 'http://www.domain.com/') as new_prop_url"))
    ->orderBy('prop_id', 'desc')
    ->limit(6)
    ->get();
然后在您看来,您可以这样做:
@if(isset($featuredProperties))
   @foreach ($featuredProperties as $property)
       <li>
           <a title="{{ $property->prop_name }}" href="{{ $property->new_prop_url }}"></a>
       </li>           
  @endforeach
@endif
我想您可能正在寻找一个集合宏。你可以用你AppServiceProvider喜欢的方式注册它:
Collection::macro('formatPropUrl', function() {
    return collect($this->items)->map(function($property) {
        $property->prop_url=str_replace("http://domain.com/","http://www.domain.com/",$property->prop_url);
        return $property;
    });
});
然后对于您的查询,您可以执行以下操作:
$featuredProperties = DB::table('properties')
    ->where([
        ['featured_property', '=', '1'],
        ['supplier_id', '=', 123],
    ])
    ->orderBy('prop_id', 'desc')
    ->limit(6)
    ->get()
    ->formatPropUrl();
| 归档时间: | 
 | 
| 查看次数: | 381 次 | 
| 最近记录: |