因此,在下面的代码中,我必须每次查询数据库中的每个图像。太慢了。有没有办法在一个查询中做到这一点,同时将实际的图像urls隐藏起来,就像我目前在刀片文件中所做的那样?
刀片:
<img src="/image/1">
<img src="/image/2">
<img src="/image/3">
路由:
Route::get('/image/{id}', [ImageController::class, 'image']);
主计长:
public function image($id)
{
$img = DB::where('id', '=', $id)
->select('path', 'filename', 'extension')
->first();
$image_path = $img->path.'/'.$img->filename.$img->extension;
return response()->file( $image_path );
}
我基本上是从数据库获得链接和图像应该是可访问的,而不必登录。我只想隐藏文件名,而不必将实际的文件名更改为散列ids。之所以如此,是因为文件名帮助我识别我在看什么。我只想在浏览器中隐藏文件名,而不必牺牲性能。
发布于 2022-08-22 17:28:07
这看起来是一个完美的视图编写器候选人
app\Composers\ImageComposer.php
(新文件夹app\Composers
中的新文件)
<?php
namespace App\Providers\Composers;
use App\Models\Image;
use Illuminate\View\View;
class ImageComposer {
public function compose(View $view) {
// Note: Important to use an `Image` model here for extended functionality
$images = Image::whereIn('id', [1, 2, 3])->get();
return $view->with(['images' => $images]);
}
}
app\Providers\AppServiceProvider.php
) (现有文件)
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Providers\Composers\ImageComposer;
class AppServiceProvider extends ServiceProvider {
public function boot() {
view()->composer('images', ImageComposer::class);
}
}
app\Models\Image.php
(新的或现有的模型)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Image extends Model {
public function getDisplayPathAttribute() {
return $this->path. '/' . $this->filename . $this->extension;
}
public function getBase64EncodedStringAttribute() {
return 'data:image/' . $this->extension . ';base64,' . base64_encode(file_get_contents($this->display_path));
}
}
images.blade.php
( /images/1
等代码所在的现有文件)
@foreach($images as $image)
<img src="{{ $image->display_path }}"/>
<!-- OR -->
<img src="{{ $image->base64_encoded_string }}"/>
@endforeach
这里的基本逻辑是,images.blade.php
是一个view
,编写器创建一个$images
变量,然后您可以迭代该变量并使用display_path
填充src
属性,该属性是用于返回完整路径的Image
模型的访问器。每当您呈现images.blade.php
视图时,无论是通过@include('images')
还是view('images')
等等,它都会使$images
可用。
https://stackoverflow.com/questions/73447682
复制相似问题