Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mohamud's avatar

I am getting this error ErrorException Trying to get property 'title' of non-object

How do I solve it

0 likes
36 replies
mohjacksi's avatar

Hi Mohammed, please insert your code that occurring with this problem, for now, if you're using PHP 8 you can write like this:

$object?->title; 

then if the object is null, then this exception wouldn't appear for your or you can use:


if(isset($object)){
			$object->title;
}

because your object it maybe null, like when you search for an object not exist in you database, like looking for a user with name lalalalalala, it would return null;

Mohamud's avatar

When i dd(Post::find($slug)); i am getting null and the error is coming from my posts.blade.php file

1 like
mohjacksi's avatar

@Mohamud When you are using find on your Post model, you're searching by id, Laravel doesn't know that you're looking in slug column, then instead of Post::find($slug) you have to change it like: Post::where('slug',$slug)->first(); and you should make sure that your column is 'slug' which pased in the first argument of where() function

martinbean's avatar

How do I solve it

@mohamud By reading the error message.

You’re calling ->title on something that isn’t an object. So go to the file and line the error message says it is occurring.

1 like
martinbean's avatar

@Mohamud So debug your code. Find out why it’s undefined and not what you’re expecting it to be.

SilenceBringer's avatar

@mohamud is it a trolling? everyone asked you to show some code to help you, but you didn't. Do you think we want to imagine everything?

Mohamud's avatar

i did share some of the code

this is my posts.blade.php

My Blog // Here is the error Undefined variable '$posts'

Go Back

I am getting the same error

Mohamud's avatar

I want to share in that format but dont know how thats why i am copy pasting code

Mohamud's avatar
<!DOCTYPE html>
<html lang="en">
<head>
    <title>My Blog</title>
    <link rel="stylesheet" href="/app.css">
</head>
<body>
    <article>
       <h1> {{ $post->title }} </h1>
        <div>
            {!! $post->body !!}
        </div>
    </article>
    <a href="/">Go Back</a>
</body>
</html>

Mohamud's avatar

the error is on line 9 Trying to get property 'title' of non-object

SilenceBringer's avatar

@Mohamud I understand. it's because you didn't pass post to the view correctly. To figure it out - show your controller

Mohamud's avatar

@SilenceBringer

I have nothing in my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
SilenceBringer's avatar

@Mohamud it's base controller. Your route should calls another controller made by you. SHow your routes/web.php

Mohamud's avatar

@SilenceBringer

<?php

use App\Models\Post;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;




/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('posts', [
        'posts' => Post::all()
    ]);

});

Route::get('posts/{post}', function ($slug) {
    return view('post', [
        'post' => Post::find($slug)
    ]);
})->where('post', '[A-z_\-]+');
SilenceBringer's avatar

@Mohamud almost there! I think here Post::find($slug) you have null. Replace it with

        'post' => Post::findOrFail($slug)

by default find search by id. Did you set correct primary key to search by slug? https://laravel.com/docs/8.x/eloquent#primary-keys

class Post extends Model
{
    protected $primaryKey = 'slug';
}

or search by slug like

        'post' => Post::where('slug', $slug)->first()
Mohamud's avatar

@SilenceBringer

<?php

namespace App\Models;

use Illuminate\Support\Facades\File;
use Spatie\YamlFrontMatter\YamlFrontMatter;

class Post
{

    public $title;
    public $excerpt;
    public $date;
    public $body;
    public $slug;

    public function __construct($title, $excerpt, $date, $body, $slug)
    {
        $this->title = $title;
        $this->excerpt = $excerpt;
        $this->date = $date;
        $this->body = $body;
        $this->slug = $slug;
    }

    public static function all()
    {
        return cache()->rememberForever('posts.all', function () {
            return collect(File::files(resource_path("posts")))
                ->map(fn($file) => YamlFrontMatter::parseFile($file))
                ->map(fn($document) => new Post(
                    $document->title,
                    $document->excerpt,
                    $document->date,
                    $document->body(),
                    $document->slug,

                ))
                ->sortByDesc('date');

        });
    }
    public static function find($slug) {
        return static::all()->firstWhere('slug', $slug);
    }
}

Snapey's avatar

@Mohamud where did you copy this from?

do you have a bunch of static files?

Mohamud's avatar

@Snapey yes i have html files that have this

        ---
        title: My Fourth Post
        slug: my-fourth-post
        excerpt: Lorem ipsum dolor sit amet
        date: 2021-10-02
        ---
<p>
    Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque harum dicta iusto mollitia molestias vel delectus cupiditate accusamus aperiam pariatur cum, quod ipsum laboriosam similique facilis inventore enim illo culpa.
    Labore fugit accusantium quasi fuga beatae quibusdam praesentium ea fugiat et aliquid expedita, eligendi odio culpa suscipit numquam eos? Autem impedit quas quidem non cum omnis cumque tempore veniam ea!
    Natus illo aperiam at placeat mollitia eaque odit laudantium ex voluptatem ipsum cupiditate sed error autem ab inventore culpa sunt, possimus provident! Beatae maxime quisquam voluptas nobis sed eveniet cumque!
</p>
Snapey's avatar

open tinker, run App\Models\Post::all()

What do you get?

Mohamud's avatar

@Snapey

=> Illuminate\Support\Collection {#3485
     all: [
       App\Models\Post {#3486
         +title: null,
         +excerpt: null,
         +date: null,
         +body: """
                   ---\n
                   title: My First Post\n
                   excerpt: Lorem ipsum dolor sit amet\n
                   slug: my-first-post\n
                   date: 2021-10-02\n
                   ---\n
                   <p>\n
                       Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque harum dicta iusto mollitia molestias vel delectus cupiditate accusamus aperiam pariatur cum, quod ipsum laboriosam similique facilis inventore enim illo culpa.\n
                       Labore fugit accusantium quasi fuga beatae quibusdam praesentium ea fugiat et aliquid expedita, eligendi odio culpa suscipit numquam eos? Autem impedit quas quidem non cum omnis cumque tempore veniam ea!\n
                       Natus illo aperiam at placeat mollitia eaque odit laudantium ex voluptatem ipsum cupiditate sed error autem ab inventore culpa sunt, possimus provident! Beatae maxime quisquam voluptas nobis sed eveniet cumque!\n
                   </p>\n
           """,
         +slug: null,
       },
       App\Models\Post {#3487
         +title: null,
         +excerpt: null,
         +date: null,
         +body: """
                   ---\n
                   title: My First Post\n
                   excerpt: Lorem ipsum dolor sit amet\n
                   slug: my-first-post\n
                   date: 2021-10-02\n
                   ---\n
                   <p>\n
                       Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque harum dicta iusto mollitia molestias vel delectus cupiditate accusamus aperiam pariatur cum, quod ipsum laboriosam similique facilis inventore enim illo culpa.\n
                       Labore fugit accusantium quasi fuga beatae quibusdam praesentium ea fugiat et aliquid expedita, eligendi odio culpa suscipit numquam eos? Autem impedit quas quidem non cum omnis cumque tempore veniam ea!\n
                       Natus illo aperiam at placeat mollitia eaque odit laudantium ex voluptatem ipsum cupiditate sed error autem ab inventore culpa sunt, possimus provident! Beatae maxime quisquam voluptas nobis sed eveniet cumque!\n
                   </p>\n
           """,
         +slug: null,
       },
       App\Models\Post {#3483
         +title: null,
         +excerpt: null,
         +date: null,
         +body: """
                   ---\n
                   title: My Fourth Post\n
                   excerpt: Lorem ipsum dolor sit amet\n
                   slug: my-fourth-post\n
                   date: 2021-10-02\n
                   ---\n
           <p>\n
               Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque harum dicta iusto mollitia molestias vel delectus cupiditate accusamus aperiam pariatur cum, quod ipsum laboriosam similique facilis inventore enim illo culpa.\n
               Labore fugit accusantium quasi fuga beatae quibusdam praesentium ea fugiat et aliquid expedita, eligendi odio culpa suscipit numquam eos? Autem impedit quas quidem non cum omnis cumque tempore veniam ea!\n
               Natus illo aperiam at placeat mollitia eaque odit laudantium ex voluptatem ipsum cupiditate sed error autem ab inventore culpa sunt, possimus provident! Beatae maxime quisquam voluptas nobis sed eveniet cumque!\n
           </p>\n
           """,
         +slug: null,
       },
       App\Models\Post {#3490
         +title: null,
         +excerpt: null,
         +date: null,
         +body: """
                   ---\n
                   title: My Second Post\n
                   slug: my-second-post\n
                   excerpt: Lorem ipsum dolor sit amet\n
                   date: 2021-10-02\n
                   ---\n
                   <p>\n
                       Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque harum dicta iusto mollitia molestias vel delectus cupiditate accusamus aperiam pariatur cum, quod ipsum laboriosam similique facilis inventore enim illo culpa.\n
                       Labore fugit accusantium quasi fuga beatae quibusdam praesentium ea fugiat et aliquid expedita, eligendi odio culpa suscipit numquam eos? Autem impedit quas quidem non cum omnis cumque tempore veniam ea!\n
                       Natus illo aperiam at placeat mollitia eaque odit laudantium ex voluptatem ipsum cupiditate sed error autem ab inventore culpa sunt, possimus provident! Beatae maxime quisquam voluptas nobis sed eveniet cumque!\n
                   </p>\n
           """,
         +slug: null,
       },
       App\Models\Post {#3491
         +title: null,
         +excerpt: null,
         +date: null,
         +body: """
                   ---\n
                   title: My Third Post\n
                   excerpt: Lorem ipsum dolor sit amet\n
                   slug: my-third-post\n
                   date: 2021-10-02\n
                   ---\n
                   <p>\n
                       Lorem, ipsum dolor sit amet consectetur adipisicing elit. Itaque harum dicta iusto mollitia molestias vel delectus cupiditate accusamus aperiam pariatur cum, quod ipsum laboriosam similique facilis inventore enim illo culpa.\n
                       Labore fugit accusantium quasi fuga beatae quibusdam praesentium ea fugiat et aliquid expedita, eligendi odio culpa suscipit numquam eos? Autem impedit quas quidem non cum omnis cumque tempore veniam ea!\n
                       Natus illo aperiam at placeat mollitia eaque odit laudantium ex voluptatem ipsum cupiditate sed error autem ab inventore culpa sunt, possimus provident! Beatae maxime quisquam voluptas nobis sed eveniet cumque!\n
                   </p>\n
           """,
         +slug: null,
       },
     ],
   }
>>> 
Snapey's avatar

So your problem is that your Post model is not parsing the file correctly.

The title field is not mapped to the title attribute

You will see here

       App\Models\Post {#3491
         +title: null,
         +excerpt: null,
         +date: null,
         +body: """

The file appears to not be in the correct yaml format

johnDoe220's avatar

for read post with route model binding

Route::get('posts/{post}', function (Post $post) {
    return view('post', [
        'post' => $post;
    ]);
})->where('post', '[A-z_\-]+');
// and this write into post model
public function getRouteKeyName()
{
	return 'slug';
}

Please or to participate in this conversation.