laravel 中的随机图像

Random images in laravel

我有一个名为 random_img 的数据库 table。里面有 10 行 10 张图片。

我将从 public/images/random

中提取图像

我想使用数据库,这样我就可以将循环设置为 Random take(1)。我想在我的英雄形象中使用。 (每页刷新新图片)

我应该在哪里放置我的数据库查询以便我可以在全球范围内使用它?或者我如何使用我的 RandomImgsController 以便它在全球范围内使用?

我创建了一个路由文件,因此我可以在需要时将其用作包含。

路线:

Route::post('/layouts/inc/random-img','RandomImgsController@randomimg')->name('random-img');

包括:

@include('layouts.inc.random-img')

里面包括:

  @foreach ($randomimg as $rand)
  <span class="hero-image">
            <img src="/images/random/{{$rand->file_name}}" class="img--max--hero blur-img">
            </span>
@endforeach

RandomImgsController:(这个应该去哪里,这样我就可以全局使用了)

public function randomimg()
{
    $randomimg = DB::table('randomimg')->orderBy(DB::raw('RAND()'))->get();
    return view('random-img',compact('randomimg'));
}}

这是我想在我网站的每个页面上实现的:

@php
$randomimg = DB::table('randomimg')->orderBy(DB::raw('RAND()'))->get()->take(1);    
@endphp
  @foreach ($randomimg as $rand)
  <span class="hero-image">
            <img src="/images/random/{{$rand->file_name}}" class="img--max--hero blur-img">
            </span>
@endforeach

执行此操作的更简洁方法是什么?

更新:

我现在可以在所有视图中访问 images 数据库,但我遇到了问题。

在我的 App\Http\ViewComposer\ImageComposer.php 文件中我有这个:

public function compose(View $view)
{
    $view->with('foo', Image::inRandomOrder()->get()->take(1));
}

在任何视图中,我都可以使用 {{$foo}} 从我的图像中获取随机行 table,但数据以这样的字符串形式出现:

[{"id":10,"alt":"Image Alt Tag","title":"Image Title","file_name":"10.jpg"}]

当我尝试像这样只抓取单个列时 {{$foo->file_name}}

我收到错误:

Property [file_name] does not exist on this collection instance.

我怎样才能像这样抓取单独的列:{{$foo->alt}}{{$foo->title}}{{$foo->file_name}} 然后在我的视图中干净地输出它们?例如,我需要 {{$foo->file_name}} 来渲染:5.jpg.

更新 2: 我想到了。必须使用 @foreach 因为我使用的是 get() 方法。

@foreach($foo as $f)
{{$f->file_name}}
@endforeach

仍然想知道是否有没有 get() 方法的方法。不过这会起作用。

首先,您不能在 blade 模板中 @include 路由。您实际要做的是从您的 blade 模板向您创建的路由发送一个 AJAX 请求以检索随机图像。然而...

听起来控制器在这种情况下的逻辑位置不对。

假设您有一个关联的 Eloquent 模型用于您的 table,一个简单的选择可能是在您的 RandomImage 模型上定义一个方法(可能只是被称为 Image).

这样,您可以只使用 Image 模型生成随机图像并将其传递到您想要的任何视图。然后也不需要在每个页面重新加载时查询每个图像。您每次请求只会查询一张图片。

想象一下,如果您视图中的代码看起来像这样:

<span class="hero-image">
    <img 
        src="{{ $image->url() }}" 
        class="img--max--hero blur-img" />
</span>

例如,这可能属于主页,这听起来就像您正在尝试做的那样。所以也许你有这样的路线:

Route::get('/', function () {
    $image = App\Image::random();
    return view('home', compact('image');
});

您可以在 Image 模型上使用查询范围来实现此目的:

public function scopeRandom($query)
{
    return $query->inRandomOrder()->first();
}

编辑

如果您希望在您网站的许多甚至所有视图中使用它,您可以使用 View Composer:https://laravel.com/docs/5.6/views#view-composers

您的撰写方法如下所示:

public function compose(View $view)
{
    $view->with('image', Image::random());
}

并且 View Composer 将在您的 AppServiceProviderComposerServiceProvider 等新提供程序中注册。在 boot 方法中你需要:

public function boot()
{
    // Using class based composers...
    View::composer(
        '*', 'App\Http\ViewComposers\ImageComposer'
    );
}

其中 * 表示您希望将此作曲家应用于所有视图。