Bilawal Awan
Bilawal Awan

Reputation: 432

Trying to get property of non-object in laravel 5.8

i want to show the name of the category in post table but this give me error here my code check this

this is the modal

<?php

namespace App;

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

class Post extends Model
{

    protected $fillable=['seotitle', 'h1title', 'image' , 'alt', 'url' , 'meta','author','status','keywords', 'tags', 'category_id', 'text','read', 'view'];


    public function Category(){

        return $this->belongsTo(Category::class);
    }
}

i also use the fillable for 'name' in category modal

post controller

namespace App\Http\Controllers;
use DB;
use App\Post;
use App\categoriesegory;
use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostsRequest;
use App\Http\Requests\Posts\UpdatePostRequest;
use Illuminate\Support\Facades\Storage;
public function index()
    {
        // $select=DB::select("SELECT * From posts where status='publish'");    
        return view('/admin/posts/index')->with('posts' , Post::all());
    }

blade file

<td>{‌{$post->Category->name}}</td>

Category= this is modal function name in relationship

how can i solve this issue ?

i want to show the name of category in the post table but getting error can you show me what the issue laravel 5.8

Upvotes: 1

Views: 1614

Answers (2)

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

In your controller file.

public function index()
{
    $posts = Post::all();
    return view('admin/posts/index',compact('posts'));
}

Use in blade file.

@if(!empty($posts))
    @foreach($posts as $post)

       <td>{‌{$post->Category->name ?? '' }}</td>
    @endforeach
@endif

Upvotes: 3

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

Error occur because one post did not have category. You must be use.

<td>{‌{$post->Category->name ?? ''}}</td> 

Upvotes: 0

Related Questions