Laravel Non-static method issue

Alex picture Alex · Jan 2, 2013 · Viewed 16.2k times · Source

Having the following Models:

news.php

class News extends Aware {

    public static $table = 'noticia';
    public static $key = 'idnoticia';
    public static $timestamps = false;

    public static $rules = array(
        'titulo' => 'required',
        'subtitulo' => 'required',
    );

    public function images()
    {
        return $this->has_many('Image');
    }
}

image.php

class Image extends Aware {

    public static $timestamps = true;

    public static $rules = array(
        'unique_name' => 'required',
        'original_name' => 'required',
        'location' => 'required',
        'news_id' => 'required',
    );

    public function news()
    {
        return $this->belongs_to('News');
    }

}

Then in a controller I do the following:

$image = new Image(array(
    'unique_name' => $fileName,
    'original_name' => $file['file']['name'],
    'location' => $directory.$fileName,
    'news_id' => $news_id,
));
News::images()->insert($image);

I keep getting the following error message:

Non-static method News::images() should not be called statically, assuming $this from incompatible context

Any ideas what am I doing wrong?

Setting public static function images() doesn't seem to be wanted, as after a refresh I get an error saying

$this when not in object context

Gordon said that by doing News::images()->insert($image); I'm doing a static call, but that's how saw to do it

Answer

Halcyon picture Halcyon · Jan 2, 2013

You're using $this in a function that is called statically. That's not possible.

$this becomes available only after you create an instance with new.

If you turn on strict mode you will get another error, namely that images is not a static function and thus shouldn't be called statically.

The problem is in News::images(), not in images()->insert($image);