如何在 laravel 5 中绑定响应数据以查看


How to bind response data to view in laravel 5

我正在尝试在元素上显示图像,但它不起作用,当我只是返回数据时,它的显示图像。

路线.php

Route::get('/dashboard',function() {
       $Image = Auth::user()->profile_pic;
       $type = 'image/jpeg';
       $img = response($Image)->header('Content-Type', $type);
       return View::make('dashboard', ['img'=>$img]);
     });

仪表板.刀片.php

<img src={{ $img }} class="img-circle" width="200" height="200">

请帮忙。

您应该添加一个路由,以便在将请求发送到指定的 URL 时,从数据库中读取头像并将其作为图像/jpeg 发送到浏览器。

例如,将以下代码添加到您的routes.php

Route::any('/user/{user}/profile-pic',
    function('App'User $user) {
       $Image = Auth::user()->profile_pic;
       return response($Image)->header('Content-Type', 'image/jpeg');
    });

修改/dashboard 路由以使用此新路由

Route::get('/dashboard',function() {
       $id = Auth::user()->id;
       $imageUrl="/user/$id/profile-pic";
       return view('/dashboard', ['imageUrl' => $imageUrl]);
     });

最后,在您看来,绑定新变量

<img src="{{$imageUrl}}" class="img-circle" width="200" height="200">

Auth::user()->profile_pic是用户头像的网址吗?如果是这样,只需使用

return View::make('dashboard', ['img'=>Auth::user()->profile_pic]);

另外,在 src 属性中添加引号:

<img src="{{ $img }}" class="img-circle" width="200" height="200">

重要的是要知道

$img = response($Image)->header('Content-Type', $type);

是一个Illuminate'Http'Response的响应对象,但在HTML中你需要一个指向图像的链接,一个string,而不是一个Response