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

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I tried that but in static function $this-> not works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.