Home > other >  where could i be wrong? Trying to get property 'title' of non-object
where could i be wrong? Trying to get property 'title' of non-object

Time:05-02

when trying to view a specific blog article i get the error Trying to get property 'title' of non-object here is my controller controller code

  public function theblog(Request $req, $slug){
    $blog = blog::find($slug);
    DB::table("blogs")->where('slug', "$slug")->increment('views');
    return view('myblog',compact('blog'));  
}

CodePudding user response:

  public function theblog(Request $req, $slug){
    $blog = blog::where('slug', $slug)->firstOrFail();
    DB::table("blogs")->where('slug', $slug)->increment('views');
    return view('myblog',compact('blog'));  
}

Some tips.

  • your primary key is unlikely to be 'slug' so you need to use a where
  • don't quote php parameters
  • your classes should start with an uppercase, ie Blog not blog
  • you should probably only increment views once per user

CodePudding user response:

public function theblog(Request $req, $slug){ $blog = blog::find($slug);
dd($slug); 
 DB::table("blogs")->where('slug', "$slug")->increment('views'); return view('myblog',compact('blog')); } 

Check if there is value for $blog...if it is null(that is the problem) then you should check you DB?

  • Related