显示数据库中的文章第一张图片作为封面图片

时间:2018-11-06 23:32:40

标签: php arrays json laravel laravel-5

我在Articles表中有images字段,并且我会将所有图像保存为该数组:images/image1.jpg,images/image2.jpg, ...

在我的索引页面中,我将获取所有文章并将其显示在主页中:

$articles = \App\Article::all();

我只想从每篇文章中加载第一张图像作为封面图像并显示出来,但是images字段是字符串。我该怎么办?

       @foreach($articles as $article)
        <div class="article_wrapper">
            <div class="article_body">
                    @foreach($article->images as $image)
                        {{ $image }}
                    @endforeach
            </div>
        </div>
      @endforeach

1 个答案:

答案 0 :(得分:0)

仅使用路线:

Route::any('/article/images/{id}', ['as' => 'article.image', function($id) {

    $article = Article::find($id);

    $images = explode(',',$article->images);

    return Response::download($images[0]);
}]);

使用控制器:

namespace MyNamespace;

use Illuminate\Routing\Controller;
use App\Article;
use Response;

class ImagesController extends Controller
{
    public function show($id)
    {
        $article = Article::find($id);

        $images = explode(',',$article->images);

        return Response::download($images[0]);
    }
}

您的路线:

Route::get('/article/images/{id}', ['as' => 'article.image', 'uses' => 'MyNamespace\ImagesController@show']);

然后在您看来:

<img src="{{route('article.image', ['id' => $article->getKey()])}}" />

这样您的视图将如下所示:

@foreach($articles as $article)
    <div class="article_wrapper">
        <div class="article_body">
            <img src="{{route('article.image', ['id' => $article->getKey()])}}" />
        </div>
    </div>
@endforeach

如果您没有在图像字段中保存完整路径,请在其前面加上前缀:

return Response::download('C:\downloadpath\' . $images[0]);