Laravel - 尝试获取非对象的属性:: first()

时间:2018-01-05 17:18:35

标签: php laravel laravel-5 laravel-query-builder

好的,当我尝试使用Trying to get property of non-object

从数据库获取数据时,我获得$settings = AdminSettings::first();

这是控制器代码

    <?php

namespace App\Http\Controllers\AdminSettings;

use App\AdminSettings\AdminSettings;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminSettingsController extends Controller
{
    public function index()
    {
        $settings = AdminSettings::first();

        return view('admins.settings.settings', compact('settings'));
    }
}

这是模态代码

    <?php

namespace App\AdminSettings;

use Illuminate\Database\Eloquent\Model;

class AdminSettings extends Model
{
    protected $table = 'site_settings';
    protected $fillable = [
        'site_title', 'site_url', 'email_from', 'email_to', 'timezone', 'date_format', 'time_format',
    ];
}

这里我试图放site_title into the input but I get Trying to get property of non-object

<div class="form-group">
                        <label for="site_title" class="form-label">Site Title</label>
                        <input type="text" class="form-control" name="site_title" id="site_title" value="{{ $settings->site_title }}"/>
                    </div>

当我尝试dd($settings);时,我得到null

4 个答案:

答案 0 :(得分:7)

您表示该表为空,因此请设置对象optional

{{ optional($settings)->site_title }}

答案 1 :(得分:0)

使用find()获取单个集合

$settings = AdminSettings::find($id);

您也可以使用first

 $settings = AdminSettings::where('id',$id)->first();

如果您需要整个收藏,请使用all()

$settings = AdminSettings::all();

在您看来,请使用 -

进行简单检查
<input type="text" class="form-control" name="site_title" id="site_title" value="<?php echo ($settings)?$settings->site_title:'' >"/>

答案 2 :(得分:0)

您也可以使用or运算符:

{{ $settings->site_title or ''  }}

答案 3 :(得分:0)

使用empty来检查对象:

@if(!empty($settings->site_title))
  {{ $settings->site_title }}
@else
  "Nothing"
@endif