There is a model Post

<?php namespace App; use Carbon\Carbon; use Illuminate\Support\Facades\Storage; use Illuminate\Database\Eloquent\Model; use Cviebrock\EloquentSluggable\Sluggable; use Illuminate\Support\Facades\Auth; class Post extends Model { use Sluggable; const IS_DRAFT = 0; const IS_PUBLIC = 1; protected $fillable = ['title','content', 'date', 'description']; public function comments() { return $this->hasMany(Comment::class); } public function getComments() { return $this->comments()->where('status', 1)->get(); } } 

In the controller, no method is invoked to any method, but only the entire model is being referred to, the desired article.

 public function show($slug) { $post = Post::where('slug', $slug)->firstOrFail(); return view('pages.show', compact('post')); } 

And in the form, the method is called $ post-> getComments , how did this method get into view, if in the controller, it was not passed? or when there is any appeal to the class, in this way Post :: then all methods are stitched into the variable?

    1 answer 1

    You in the controller received a copy of the Post model and transfer this copy to the waters. And there is no difference where you use this instance with all its methods — in the controller, view, console command, task, event handler, etc.
    Well, another moment. Since this is a class method, then it should be called as a method: $ post-> getComments ()

    • How did I get it, if usually, through the colon, there is an appeal to static methods, without creating an instance? - DivMan
    • Static laravel methods use the new static () call inside themselves and return an instance)) Read the topic about static binding later - Max By