Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Trying to get property of non-object on ::first()

Ok so I'm getting Trying to get property of non-object when I try and get the data from the DB using $settings = AdminSettings::first();

here is the controller code

    <?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'));
    }
}

here is the modal code

    <?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',
    ];
}

here I'm trying to put the 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>

when I try to dd($settings); i get null

like image 208
Yosef Avatar asked Jan 05 '18 17:01

Yosef


2 Answers

You've said the table is empty, so make settings object optional:

{{ optional($settings)->site_title }}
like image 88
Alexey Mezenin Avatar answered Nov 19 '22 03:11

Alexey Mezenin


You can use or operator too:

{{ $settings->site_title or ''  }}
like image 31
YouneL Avatar answered Nov 19 '22 05:11

YouneL