Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 328
Rey Norbert Besmonte Avatar asked Jul 29 '26 03:07

Rey Norbert Besmonte


2 Answers

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

like image 103
Niklesh Raut Avatar answered Jul 30 '26 19:07

Niklesh Raut


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();
like image 42
chanafdo Avatar answered Jul 30 '26 19:07

chanafdo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!