'Trying to get property of a non-object problem in laravel

I am working on a laravel project. In this project, if a non-user tries to edit a post then it will redirect to the posts page without letting the user make any edit. But I am getting this error

Trying to get property of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php).

ErrorException (E_ERROR) Trying to get property of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php) Previous exceptions and may be it might help Trying to get property of non-object (0) ErrorException {#221 ▼ #message: "Trying to get property of non-object" #code: 0 #file: "C:\xampp\htdocs\lsapp\storage\framework\views\b4b78b7a31531d4e8ddf98112cc09d54ba62ed99.php" #line: 3 #severity: E_NOTICE }

Here is the edit code:

 public function edit($id)
    {
        $post = Post::find($id);
        if(auth()->user()->id !== $post->user_id){
            return redirect ('posts')->with('error','Unauthorized page');
        } 
        return view('posts.edit')->with('post',$post);
    }

PostsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use DB;

class PostsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth',['except'=>['index','show']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //$posts=Post::all();
        //$posts=Post::orderBy('title','desc')->get();
        //return Post::where('title','post two')->get();
        //$posts=DB::select("SELECT * FROM posts");
        //$posts= Post::orderBy('title','desc')->take(1)->get();
        $posts= Post::orderBy('created_at','desc')->paginate(1);
        
        return view('posts.index')->with('posts',$posts);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('posts.create');

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'title'=>'required',
            'body'=>'required'
        ]);
        //Create posts
        $post=new Post;
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->user_id=auth()->user()->id;
        $post->save();

        return redirect('posts')->with('success','Post Created');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $post = Post::find($id); 
        return view('posts.show')->with('post',$post);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $post = Post::find($id);
        if(auth()->user()->id !== $post->user_id){
            return redirect ('posts')->with('error','Unauthorized page');
        } 
        return view('posts.edit')->with('post',$post);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'title'=>'required',
            'body'=>'required'
        ]);
        //Create posts
        $post=Post::find($id);
        $post->title = $request->input('title');
        $post->body = $request->input('body');
        $post->save();

        return redirect('posts')->with('success','Post Updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    public function destroy($id)
    {
        $post=Post::find($id);
        $post->delete();
        return redirect('posts')->with('success','Post Deleted');

    }
}

show.blade.php:

@extends('layouts.app')

@section('content')
       <a href="{{route('posts.index')}}" class="btn btn-default">Back</a> 
       <h1>{{$post->title}}</h1>

       <div>
            {{$post->body}}
       </div>
       <hr>
       @if(!Auth::guest())
       @if(Auth::user()->id==$post->user_id)
       <small>Witten on {{$post->created_at}} by {{$post->user->name}}</small>

       <hr>
       <a href="{{$post->id}}/edit" class="btn btn-default">Edit</a>
       {!!Form::open(['action'=>['PostsController@destroy',$post->id],'method'=>'POST', 'class'=>'pull-right'])!!}
       {{Form::hidden('_method','DELETE')}}
       {{Form::submit('Delete',['class'=>'btn btn-danger'])}}
       {!!Form::close()!!}
       @endif

       @endif
       @endsection

here is my route:

Route::get('/index', 'PagesController@index');
Route::get('/about', 'PagesController@about');
Route::get('/services', 'PagesController@services');

Route::resource('/posts','PostsController');

Auth::routes();

Route::get('/dashboard', 'DashboardController@index');

Here is user.php in case it helps

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function posts(){
        return $this->hasMany('App\Post');
    }
}


Solution 1:[1]

Look in your blade file. Whenever you all $post->user->SOMEPROPERTIES, change it to $post->user['SOMEPROPERTIES']

Example:

   <small>Witten on {{$post->created_at}} by {{$post->user['name']}}</small>

I hope it will work for you. (Working in my case)

Solution 2:[2]

Look in your blade file. Whenever you all $post->user->SOMEPROPERTIES, change it to $post->user()

like here:

   <small>Witten on {{$post->created_at}} by {{$post->user()->name}}</small>

Solution 3:[3]

check your href value. Check the curly braces

Wrong code:

@foreach($posts as $post)
    <a href="/posts/{$posts->id}">the text of the link</a>
@endforeach

Working code:

@foreach($posts as $post)
    <a href="/posts/{{$post->id}}">the text of the link</a>
@endforeach

I hope this helps in some way.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Misbakh Ahmed
Solution 2 Raffobaffo
Solution 3 Ahmed Aboud