Rey Norbert Besmonte
Rey Norbert Besmonte

Reputation: 791

Php Laravel call a function in the same model

I have a model with 2 functions. Let's say the model's name is Cars. I am trying to call one function brand that returns an array so I can use it inside the other getBrand function.

public static function getBrand($data) {
    $brandVariable = $this->brand(); 
    for ($i=1; $i < count($brandVariable ) ; $i++) { 
        //do something
    }
}

public static function brand() {
    $arrayValues = array(
         1 => 'Brand A',
         2 => 'Brand B',
    );
    return arrayValues;
}

Since the values are in brand function, I need to pass it inside getBrand.

I am getting an error in the for loop. I tried in another file (local PHP not Laravel) and it is working fine. But in Laravel, it is not getting the expected result.

Upvotes: 2

Views: 8481

Answers (3)

sajad abbasi
sajad abbasi

Reputation: 2184

the functions are static so you should use

self::brand()

instead of

$this->brand()

Upvotes: 3

chanafdo
chanafdo

Reputation: 5124

You are calling brand inside a static function and $this is not available inside the methods declared as static.

Since brand is declared as a static function you can use one of the following methods to call the function

if within the class

self::brand();

or

static::brand();

from outside of the class

ClassName::brand();

Upvotes: 5

Niklesh Raut
Niklesh Raut

Reputation: 34914

Use Cars::brand because you declared functions as static

public static function getBrand($data=null) {
    $Cars = new Cars();
    $brandVariable = $Cars::brand(); 
    for ($i=1; $i < count($brandVariable ) ; $i++) { 
        //do something
    }
}

Live demo : https://eval.in/856708

Or

public static function getBrand($data=null) {
    $brandVariable = Cars::brand(); 
    for ($i=1; $i < count($brandVariable ) ; $i++) { 
        //do something
    }
}

Live demo : https://eval.in/856712

Upvotes: 6

Related Questions