Search code examples
phplaravel-5static-methodsstatic-functions

call a non static function in a static function in laravel 5


i am using laravel 5. And in a model i have a static function which i am calling in controller. It's working fine but i want same changes in this function with another non static function and when i am calling it inside static function it produce error.

Non-static method App\Models\Course::_check_existing_course() should not be called statically

Here is my model

namespace App\Models;
use Illuminate\Database\Eloquent\Model;

    class Course extends Model {
        public $course_list;
        protected $primaryKey = "id";
        public function questions(){
            return $this->belongsToMany('App\Models\Question','course_questions')->where("status",1)->orderBy("id","DESC");
        }

        public static function courses_list(){
            self::_check_existing_course();
        }
        private function _check_existing_course(){
            if(empty($this->course_list)){
                $this->course_list = self::where("status",1)->orderBy("course")->get();
            }
            return $this->course_list;
        }
    }

Solution

  • You defined your method as non-static and you are trying to invoke it as static.

    1. if you want to invoke a static method, you should use the :: and define your method as static.

    2. otherwise, if you want to invoke an instance method you should instance your class, use ->

      public static function courses_list() { $courses = new Course(); $courses->_check_existing_course(); }