如何在 @foreach 中使用函数 - Laravel

How to Use Function inside @foreach - Laravel

感谢阅读。 我是 Laravel 的新手,我想尝试使用 @foreach blade 更改数据库的输出,例如:

这是路线:

Route::get('/home', 'warnajati@index');

这是控制器:

public function index()
{
    $post = DB::table('posts')->get();
    return view('warnajati', ['posts'=>$post]);
}

这是浏览量:

 @foreach ($posts as $post)
   <div class="title"><h3>{{$post->title}}</h3></div>
 @endforeach

$post->title 的输出是 "This is The Looonger Title you ever know" , 我想用我制作的 Wordlimit() 函数使标题更短:

function wordlimit($text, $limit=10)
{
    if (strlen($text)>$limit) {
        # code...
        $word = mb_substr($text,0,$limit-3)."...";
    }else{
        $word =$text;
    }
};

我必须如何以及在何处将该功能放置在 laravel 项目中??请帮助我..

您的函数没有 return 值...Laravel 已经有此函数:http://laravel.com/docs/5.3/helpers#method-str-limit

 @foreach ($posts as $post)
   <div class="title"><h3>{{ str_limit($post->title, 10) }}</h3></div>
 @endforeach

您可以使用 Laravel's Accessor 在模型中这样做:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function getShortTitleAttribute($value)
    {
        // return shortened title here ...
    }
}

然后你可以像这样在 blade 中使用它:

{{ $post->short_title }}

希望对您有所帮助!

您可以将函数放在库文件夹中的 helpers.php 文件中。 只需确保在 composer.json 文件中自动加载了 helpers.php 文件:

"autoload": {
    "files": [
        "libraries/helpers.php"
    ],
},

如果您必须将此添加到您的 composer.json,您还必须从终端执行 运行 composer dump-autoload 命令。

有关更多信息,请查看