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

COUPDEGRACES's avatar

Trying to get property 'name' of non-object [HELP]

Hi , Initially I used this coding and it worked.

                                    <div class="blog-top">
                                        <p>By {{ $post_data->users->name }} - {{ $post_data->created_at->diffForHumans() }}</p>
                                    </div>

But when im try to acces my home page , and i got error

Trying to get property 'name' of non-object

I don't know why, even though last night it worked well, but when I try to run my project now, I get an error like that.

0 likes
31 replies
COUPDEGRACES's avatar

@sinnbeck

my modes Posts.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Posts extends Model
{
    use SoftDeletes;

    protected $fillable = ['judul','category_id','content','gambar','slug','users_id'];
    public function category(){
        return $this->belongsTo('App\Models\Category');
    }

    public function tags(){
        return $this->belongsToMany('App\Models\Tags');
    }
    public function users(){
        return $this->belongsTo('App\Models\User');
    }
    use HasFactory;
}
Sinnbeck's avatar

Change this (no s as there is one user)

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

$post_data->user->name
COUPDEGRACES's avatar

@sinnbeck still error sir,

Trying to get property 'name' of non-object (View: /home/letmeknow/Documents/BELAJAR/web/resources/views/blog.blade.php)

in blog.blade.php

 @foreach ($data as $post_data)
                        <div class="col-md-4 col-sm-6 col-xs-12">
                            <div class="single-blog mb-60">
                                <div class="blog-img">
                                    <a href="{{ route('blog.isi', $post_data->slug) }}"><img src="{{ $post_data->gambar }}" alt="blog" class="img-rounded" alt="Responsive Image"
                                        width="350" height="250" /> </a>
                                    <div class="blog-hover">

                                    </div>
                                </div>
                                <div class="blog-content">
                                    <div class="blog-top">
                                        <p>By {{ $post_data->user->name }} - {{ $post_data->created_at->diffForHumans() }}</p>
                                    </div>
                                    <div class="blog-bottom">
                                        <h2><a href="{{ route('blog.isi', $post_data->slug) }}">{{ Str::upper(Str::limit($post_data->judul,50)) }} </a></h2>
                                        <br>
                                        <a class ="btn btn-primary" href="{{ route('blog.isi', $post_data->slug) }}">Selengkapnya &raquo;</a><br>
                                    </div>
                                </div>

                            </div>
                        </div>
                        @endforeach
Sinnbeck's avatar

Can you show the migration for Posts (should be without s)

COUPDEGRACES's avatar

@sinnbeck okay sir, i make a table like this

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('judul');
            $table->integer('category_id');
            $table->text('content');
            $table->string('gambar');
            $table->string('slug');
	    $table->integer('users_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

And my users table like this

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->string('current_team_id')->nullable();
            $table->text('profile_photo_path')->nullable();
	    $table->boolean('tipe')->default(0);
            $table->timestamps();
        });
    }

my Posts Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Posts extends Model
{
    use SoftDeletes;

    protected $fillable = ['judul','category_id','content','gambar','slug','users_id'];
    public function category(){
        return $this->belongsTo('App\Models\Category');
    }

    public function tags(){
        return $this->belongsToMany('App\Models\Tags');
    }
    public function user(){
        return $this->belongsTo('App\Models\User');
    }
    use HasFactory;
}

in my BlogController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Posts;
use App\Models\Agenda;
use App\Models\Informasi;
use App\Models\Papan;
class BlogController extends Controller
{

    public function index(){
        $data = Posts::latest()->take(3)->get();
        $agenda = Agenda::latest()->take(5)->get();
        $papan = Papan::latest()->take(5)->get();
        $informasi = Informasi::latest()->take(1)->get();
        return view('blog', compact('data','agenda','papan','informasi'));

        $recent_post = Posts::latest()->take(3)->get();
        return view('blog', compact('recent_post'));
    }

    public function isi_blog($slug){
        $data = Posts::where('slug', $slug)->get();
        return view('blog.isi_post', compact('data'));
    }


}

Snapey's avatar

on the posts table, the column should be user_id not users_id

You can choose your own column names, but if you do, you have to specify them inthe relationship

Snapey's avatar

Any time you use a variable and two arrows $x->y->z then you run the risk of a crash if the middle object does not exist

You can protect against this by

{{  $post->user->name ?? 'unknown' }}

This example shows the post user name, but does not crash if the user is not known

You should consider this as a defensive measure in your code incase you have a post with no user

3 likes
Snapey's avatar

which controller method are you calling?

COUPDEGRACES's avatar

@snapey like this sir

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Posts;
use App\Models\Agenda;
use App\Models\Informasi;
use App\Models\Papan;
class BlogController extends Controller
{

    public function index(){
        $data = Posts::latest()->take(3)->get();
        $agenda = Agenda::latest()->take(5)->get();
        $papan = Papan::latest()->take(5)->get();
        $informasi = Informasi::latest()->take(1)->get();
        return view('blog', compact('data','agenda','papan','informasi'));

        $recent_post = Posts::latest()->take(3)->get();
        return view('blog', compact('recent_post'));
    }

    public function isi_blog($slug){
        $data = Posts::where('slug', $slug)->get();
        return view('blog.isi_post', compact('data'));
    }


}

so im foreach in blog.isi_post.blade.php

  @foreach ($data as $post_data)
                        <div class="col-md-4 col-sm-6 col-xs-12">
                            <div class="single-blog mb-60">
                                <div class="blog-img">
                                    <a href="{{ route('blog.isi', $post_data->slug) }}"><img src="{{ $post_data->gambar }}" alt="blog" class="img-rounded" alt="Responsive Image"
                                        width="350" height="250" /> </a>
                                    <div class="blog-hover">

                                    </div>
                                </div>
                                <div class="blog-content">
                                    <div class="blog-top">
                                        <p>By {{  $post_data->user->name ?? 'uknown' }} - {{ $post_data->created_at->diffForHumans() }}</p>
                                    </div>
                                    <div class="blog-bottom">
                                        <h2><a href="{{ route('blog.isi', $post_data->slug) }}">{{ Str::upper(Str::limit($post_data->judul,50)) }} </a></h2>
                                        <br>
                                        <a class ="btn btn-primary" href="{{ route('blog.isi', $post_data->slug) }}">Selengkapnya &raquo;</a><br>
                                    </div>
                                </div>

                            </div>
                        </div>
                        @endforeach
Sinnbeck's avatar

Does it work if you delete this line?

<p>By {{  $post_data->user->name ?? 'uknown' }} - {{ $post_data->created_at->diffForHumans() }}</p>
COUPDEGRACES's avatar

Yes sir, i f i delete it , its work when i delete this line sir

Sinnbeck's avatar

How about

<p>By {{  optional($post_data->user)->name }} - {{ $post_data->created_at->diffForHumans() }}</p>
Snapey's avatar

eager load the data in the controller;

    public function index(){
        $data = Posts::with('user')->latest()->take(3)->get();
        $agenda = Agenda::latest()->take(5)->get();
        $papan = Papan::latest()->take(5)->get();
        $informasi = Informasi::latest()->take(1)->get();
        return view('blog', compact('data','agenda','papan','informasi'));

// the two lines below will never be executed because of the above return
        $recent_post = Posts::latest()->take(3)->get();
        return view('blog', compact('recent_post'));
    }

It should not be necessary, but is good practice

COUPDEGRACES's avatar

@snapey yes sir , but im confused, last night im acces my project , its worked not error i found . but im edit functionin PostContoller

use Illuminate\Support\Facades\Auth as FacadesAuth;
        $post = Posts::create([
            'judul' => $request->judul,
            'category_id' => $request->category_id,
            'content' => $request->content,
            'gambar' => 'public/uploads/posts/'.$new_gambar,
            'slug' => Str::slug($request->judul),
            'users_id' => Auth::id()
        ]);

im changes thats code to

        $post = Posts::create([
            'judul' => $request->judul,
            'category_id' => $request->category_id,
            'content' => $request->content,
            'gambar' => 'public/uploads/posts/'.$new_gambar,
            'slug' => Str::slug($request->judul),
            'users_id' => FacadesAuth::id()
        ]);

Different only users_id .

im trying to make my controller to first step, still i get same error .

maybe i make a mistake ? :(

MichalOravec's avatar

For which reason do you use plural form of model names?

By the way if you don't want to use Auth facade you can use helper

auth()->id();
Snapey's avatar

I thought you were changing the table column to user_id

COUPDEGRACES's avatar

@michaloravec

I want to call the User from the post table, with the users_id column,

And then I created a BelongsTo relation in the Posts.php model

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

In blogcontroller

i make like this

    public function index(){
        $data = Posts::latest()->take(3)->get();
        $agenda = Agenda::latest()->take(5)->get();
        $papan = Papan::latest()->take(5)->get();
        $informasi = Informasi::latest()->take(1)->get();
        return view('blog', compact('data','agenda','papan','informasi'));

        // $recent_post = Posts::latest()->take(3)->get();
        // return view('blog', compact('recent_post'));
    }
MichalOravec's avatar
Level 75

If you use users_id as a foreign key then you have to use it in the relationship

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

By the way everytime write code in English and just in English.

3 likes
Sinnbeck's avatar

I would really suggest going over your files and correct all naming to follow the laravel convention, as @michaloravec suggested. Laravel does alot of magic but alot of it depends on proper naming.

1 like
Snapey's avatar

im already change to users_id to user_id sir, but still same error sir

its a problem if i you say you did something but did not. How are we then supposed to help?

Sinnbeck's avatar

@snapey my guess would be that the migration was changed but the database was not

1 like
endee09's avatar

Check, there is most likely a conflict of variable names, its possible you have a global variable with the same name as the local variable holding the model

Please or to participate in this conversation.