0

I have this form:

Whenever I try to enter localhost/lsapp/public/posts/edit this error is showing up:

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

How can I solve this? As I am a beginner at laravel, I am finding it hard to figure out the problem

Here is my show.blade.php file:

     @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 PostsController file:


<?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()->route('posts.index')->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');

    }
}
and route file incase it helps:
Route::get('index', 'PagesController@index');
Route::get('about', 'PagesController@about');
Route::get('services', 'PagesController@services');

Route::resource('posts','PostsController');
Oli Ullah
  • 161
  • 1
  • 2
  • 9
  • The error is telling you that your $post variable is null, or at least not an object. Ensure you have passed it into the view, and that the $post is in fact not null or an array or something else in your controller. – Kurt Friars Jun 28 '20 at 04:52
  • 1
    show the error. It directly shows where error was occurred – Nipun Tharuksha Jun 28 '20 at 05:03
  • Check weather your `$post` is an object or an array of object. – Rishabh Jha Jun 28 '20 at 05:13
  • Since the button should traverse back to domain root/posts and you have defined restful resource routes the template which should be loaded in that case is `views/posts/index.blade.php`. Obviously this is not the case or that template includes `show.blade.php`. I suggest you try to define the `Back` This ensures the correct url is inserted according to defined routing. – user3647971 Jun 28 '20 at 07:29
  • @OliUllah No problem. Glad to help. – user3647971 Jun 28 '20 at 07:34
  • @user3647971 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); } in this function whenever i try to redirect to posts page the same problem which is ErrorException (E_ERROR) Trying to get property of non-object (View: C:\xampp\htdocs\lsapp\resources\views\posts\show.blade.php) Previous exceptions showing what to do .please help me – Oli Ullah Jul 03 '20 at 05:20
  • @OliUllah Hi, does that occur after the redirect or before it? – user3647971 Jul 03 '20 at 07:27
  • I suggest you update the question with current code and show the line of code which throws the error. With that error I would need to know what code is being run and what variables have been declared and how. Then I could tell you where the problem is. – user3647971 Jul 03 '20 at 07:34
  • @OliUllah Also the index route name for the resource route is by default `posts.index`. You should use that in your redirects: `return redirect()->route('posts.index');`. Optionally you can define it with parameters if you need to redirect with id for example: `return redirect()->route('posts.show',['id' => $id]);`. More information [here](https://laravel.com/docs/7.x/redirects#redirecting-named-routes) – user3647971 Jul 03 '20 at 07:49
  • @user3647971 please have a look. In the postscontroller edit function whenever i include return redirect()->route('posts.index')->with('error','Unauthorized page'); this line the error gets showed up – Oli Ullah Jul 04 '20 at 11:31
  • @OliUllah [Here](https://stackoverflow.com/questions/19838978/laravel-redirect-back-with-message) more info on how to redirect with parameters – user3647971 Jul 04 '20 at 11:38
  • @user3647971 I have found the solution. Thanks a ton for helping me out. – Oli Ullah Jul 04 '20 at 11:56
  • @OliUllah No problem. Always fun – user3647971 Jul 04 '20 at 12:01

0 Answers0