我正在使用 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?p>
最佳答案
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/