Laravel Blade中的字符串替换

时间:2019-06-07 17:09:59

标签: php laravel laravel-5

我在Laravel 5.8中有项目。

我有此代码:

<a href="{{ route('user', ['url_address' => $user->url_address, 'id' => $user->id]) }}"><img
                                                src="{{ $user->images->first()->path ??  $placeholder }}"
                                                class="img-responsive center" alt="{{ $user->name }}"></a>

这给了我

<a href="http://name.com/user/name/2"><img src="upload/images/UserImage/c561b1742783ed038521c488d1cd59a1.jpg" class="img-responsive center" alt="angel"></a>

我需要替换为:

upload/images/UserImage/c561b1742783ed038521c488d1cd59a1.jpg

收件人:

upload/images/UserImage/thumbs3/c561b1742783ed038521c488d1cd59a1.jpg

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您在这里有一些选择。您可以更新数据库数据,添加新列以存储缩略图路径,或就地修改现有路径。

这是使用https://laravel.com/docs/5.8/helpers#method-str-replace-first

的一种方法
<?php
use Illuminate\Support\Str;

...

$search = 'upload/images/UserImage/';
$replace = 'upload/images/UserImage/thumbs3/';
$original = $user->images->first()->path;

$replaced = Str::replaceFirst($search, $replace, $original );

// Now, use `$replaced` as your image src. 
<a href="{{ route('user', ['url_address' => $user->url_address, 'id' => $user->id]) }}"> 
    <img src="{{ $replaced ??  $placeholder }}"
         class="img-responsive center" alt="{{ $user->name }}">
</a>

我还应该提到,根据我的经验,维护一个系统要容易得多,在该系统中,您存储在数据库中的所有文件都是上传文档的文件名。在这种情况下,c561b1742783ed038521c488d1cd59a1.jpg

您的视图然后控制要在哪个目录中查找:...public_path('upload/images/thumbs/' . $user->profile_image)