2

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;
        }
    }
Jitendra
  • 558
  • 8
  • 23

2 Answers2

5

From reading your code what you are trying to do is cache the results of your query on your object.

There are a couple of ways to fix this use the Cache facade (https://laravel.com/docs/5.2/cache)

Or if you just want it cached for this request in this specific case you can use a static variable.

class Course extends Model {
    public static $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 static function _check_existing_course(){
        if(is_null(self::course_list) || empty(self::course_list)){
            self::course_list = self::where("status",1)->orderBy("course")->get();
        }

        return self::course_list;
    }
}
DouglasDC3
  • 495
  • 2
  • 12
3

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(); }

Md Mahfuzur Rahman
  • 2,319
  • 2
  • 18
  • 28