php - 在 Laravel 中限制单词而不是字符

标签 php laravel laravel-5 laravel-5.7

我正在使用 Laravel 5.7 并且想知道在我从数据库中提取并输出到 Blade/ View 的描述中限制单词数量而不是字符数量的正确方法是什么。

我目前通过在我的 Blade 文件中添加以下内容来实现此目的(注意 Str 类在 Blade/view 中):

@php use Illuminate\Support\Str; @endphp
{!! (nl2br(e(Str::words($test->testimonial, '25')))) !!}

上面将我的段落限制在 25 个字以内,但我意识到我应该在我的 Controller 中使用 Str 类,而不是 Blade。

当我添加 use Illuminate\Support\Str; 时在我的 Controller 而不是 Blade 中,我得到了 Str 丢失的错误。

Controller

use App\Testimonial;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

...

public function index()
{
    $testimonial = Testimonial::all();
    return view('testimonials.index',compact('testimonial'));
}

如何在 Controller 中使用 Str 类而不是 Blade?

最佳答案

检查 Accessor and Mutator

class Testimonial extends Model
{
    public function getTestimonialExcerptAttribute()
    {
        return Str::words($this->testimonial, '25');
    }
}

然后您可以在 Blade 模板或 Controller 上使用它..

@foreach($testimonials as $testimonial)
{{ $testimonial->testimonial_excerpt }}
@endforeach

关于php - 在 Laravel 中限制单词而不是字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53472877/

相关文章:

javascript - 如何将 foreach 变量从 Laravel Blade 传递到 JavaScript?

php - 在某些 docker 主机上的第 14 行的 autoload.php 中找不到类

php - 有没有办法在 Laravel 5.2 中使用 Eloquent 一对多关系来选择列?

php - jQuery 尝试在 GET 变量中插入空格

php - Laravel 5 重置密码通知不会发送

php - 使用ajax获取javascript变量

javascript - Laravel:如何在每次单击图像时在与图像相关的弹出模式上显示动态数据

php - Laravel 调度调用 Controller

php - CakeEmail - 手动发送 HTML 和纯文本消息

PHP 和 undefined variable 策略