【问题标题】:User posts will not post but default images will用户帖子不会发布,但默认图片会
【发布时间】:2018-10-26 03:07:16
【问题描述】:

我正在创建一个博客类型的应用程序,并且在测试中我在没有图像的帖子中插入默认图像,在上传图像的帖子中插入用户图像。默认图像正确显示,但我无法让用户图像显示在帖子中。我的逻辑是检查帖子是否有 photo_id,如果有,则获取与该 photo_id 对应的文件并显示它。照片已正确上传到图像文件夹和数据库。任何帮助向我展示我做错了什么以便我可以学习将不胜感激。谢谢。

home.blade.php:

@if($posts)
                @foreach($posts as $post)
            <div class="card" style="margin-top: 20px">
                <div class="card-header">
                    <div>{{$post->user->name}}</div>
                    <div style="font-size: 10px;">{{$post->created_at->diffForHumans()}}</div>
                </div>


                <div class="card-body">
                    <div>{{$post->body}}</div>
                    <div><img height="200" src="{{$post->photo_id ? $post->file : 'http://placehold.it/400x400'}}" alt=""></div>
                </div>
            </div>
                @endforeach
                @endif

Post.php:

class Post extends Model
{
    protected $fillable = [
        'photo_id',
        'body',
        'user_id',
    ];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function photo() {
        return $this->morphMany('App\Photo', 'file');
    }
}

照片.php:

class Photo extends Model
{
    protected $fillable = [
        'file',
    ];


    public function photo() {
        return $this->morphTo();
    }
}

HomeController.php:

    public function index()
    {
        $posts = Post::all();


        return view('home', compact('posts'));
    }
}

【问题讨论】:

  • 当您在浏览器中查看src 时显示的是什么?

标签: php laravel


【解决方案1】:

试试下面的代码。在刀片模板中使用 if

@if(!empty($post->photo_id )) 
    <img height="200" src="{{ asset('/path/to/directory') }}/{{ $post->file }}" alt="">                  
@else
    <img height="200" src="http://placehold.it/400x400" alt="">   
@endif

【讨论】:

  • 应用了你的答案,现在我得到了带有 X 的小黑框,而不仅仅是空格
  • 它甚至不加载默认占位符图像吗?您是否将文件上传到任何文件夹或将图像保存为数据库中的blob
【解决方案2】:

在加载之前您不能使用关系。加载照片

$posts = Post::with('photo')->get();

【讨论】:

  • 试图添加你的答案,现在我得到错误:找不到列:1054 Unknown column 'photos.file_type' in 'where clause' (SQL: select * from photos where photos .file_id in (1, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30) 和photos.file_type = App\Post) 我正在使用 laravel 5.7跨度>
  • 因为您使用的是morphTo()。如果你正在使用这个函数,你应该传递name,type,id。在您的情况下,它应该是name,post_image,post_id
  • 非常感谢。将模型更改为 belongsTo 修复了它。谢谢。
【解决方案3】:

首先,我可以看到您只需要 photo 方法的单个结果,我建议使用 morphOne 方法。如果没有这个,下面的答案应该稍微改变一下,以适应 morphManyCollection 返回值。

正如我们所见,您尝试通过以下方式访问您的照片:

$post-&gt;file

但是查看您的代码,Post 模型类没有 file 属性。我认为这只是一个错字,你应该像这样检索你的文件:

$post-&gt;photo-&gt;file

【讨论】:

    【解决方案4】:

    如果您将图像保存在存储中,则在使用以下命令创建指向存储目录的符号链接之前,您将无法访问它:php artisan storage:link。然后你就可以访问它了。

    【讨论】:

      猜你喜欢
      • 2011-04-21
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2021-04-26
      相关资源
      最近更新 更多