【问题标题】:Laravel - Eloquent - Get specific value from return arrayLaravel - Eloquent - 从返回数组中获取特定值
【发布时间】:2020-07-09 09:36:40
【问题描述】:

我有以下代码:

     <div class="col-8
                    offset-2
                    mb-5
                    p-3
                    rounded-lg
                    shadow
                    d-flex
                    justify-content-between
                    align-items-baseline"
             style="background-color: lightgrey;
                 background-image: linear-gradient(to right, rgba(211, 211, 211, 0.52), rgba(211, 211, 211, 0.73)), url('/images/social_{{$gallery->photos->first()}}');  ">

部分代码$gallery-&gt;photos-&gt;first()返回:

{"id":3,"gallery_id":1,"filename":"IMG_3700.png","filesize":4229181,"delete":0,"created_at":"2020-03-28T09:56:31.000000Z","updated_at":"2020-03-28T09:56:31.000000Z"}

我需要访问文件名。我尝试了一些方法,但都没有奏效:

$gallery->photos->first('filename')
$gallery->photos->first()->get('filename')
$gallery->photos->first()['filename']
$gallery->photos->first()->filename

最后一次尝试 ($gallery-&gt;photos-&gt;first()-&gt;filename) 返回了这个错误:

Facade\Ignition\Exceptions\ViewException Trying to get property 'filename' of non-object (View: C:\xampp\htdocs\galshare\resources\views\home.blade.php)

如何访问返回的文件名?

谢谢

【问题讨论】:

  • $gallery-&gt;photos-&gt;first()-&gt;filename 返回什么?这应该可以工作
  • Facade\Ignition\Exceptions\ViewException Trying to get property 'filename' of non-object (View: C:\xampp\htdocs\galshare\resources\views\home.blade.php)
  • 这必须有效:$filename = null; if ($gallery &amp;&amp; !empty($gallery-&gt;photos)) {$photo = $gallery-&gt;photos-&gt;first(); $filename = $photo-&gt;filename;} 这必须适用于您显示的代码的第一行。
  • @Tpojka 谢谢,但我怎样才能让它在这里输入呢? .....social/social_{{$gallery-&gt;photos-&gt;first()}}');
  • 请改写您的问题并包含所有相关信息。你现在问的这个问题没有在上面的问题中显示。 Here is very good article of how to ask perfect question。强烈建议阅读这篇文章并相应地重写您的问题。

标签: arrays laravel eloquent


【解决方案1】:

在讨论了这个问题后,我们得出结论,$gallery 有时会返回一个空集,这是 CSS 规则生气的原因(background-image 规则中没有图像 URL)。它通过预先设置一个 php 块来解决,其中将设置默认(后备)图像 URL:

@php
$filename = '/path/to/default.jpg';
if ($gallery->isNotEmpty() && $gallery->photos->isNotEmpty()) {
    $filename = $gallery->photos->first()->filename;
}
@endphp
<style>
...
</style>

这个代码块也可以在控制器中完成,从那里可以发送$filename(即)值为$gallery-&gt;photos-&gt;first()-&gt;filename || '/path/to/fallback.jpg'的变量。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    相关资源
    最近更新 更多