alex
alex

Reputation: 7895

Laravel save class namespace in a variable or constant

I have implemented my controller like this:

class PayamAPIController extends Controller
{

    const THESIS = \App\Models\Thesis;


   public function getOffers($offerable)
     {
        // does not work
        $entities =  self::THESIS::where('user_id',\Auth::id())->get();
     }
}

this is simplifield version of my controller class.

the problem is i cant access the Thesis model via constant.

FatalErrorException in PayamAPIController.php line 27: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)

i need to store my models in constants or variables and use them inside controller methods

Upvotes: 1

Views: 1169

Answers (4)

nurzzzone
nurzzzone

Reputation: 45

You need to declare reference to constant in a variable , then call it:

class SomeController extends Controller 
{
    protected const MODEL = SomeClass::class;

    public function doSomeThing()
    {
        $entities = (self::MODEL)::where('user_id',\Auth::id())->get();  
    }
}

Upvotes: 0

alex
alex

Reputation: 7895

Found the solution. just declate reference to constant in a variable , then call it:

 $model =  self::THESIS;
 entities = $model::where('whatever')->get();

Upvotes: 0

Junaid
Junaid

Reputation: 1004

If you must use constants, try something like this

protected static $model ='App\Models\MyModel';
//in function
$model = (new static::$model)->where('id', $this->id)->firstOrFail();

or else like Claudio King mentioned include the use Model

Upvotes: 1

Claudio King
Claudio King

Reputation: 1616

No need to create a constant, just include the reference to the external Class with 'use' statement:

use \App\Models\Thesis;

class PayamAPIController extends Controller{
    $entities = Thesis::where('user_id',\Auth::id())->get();
}

Upvotes: 1

Related Questions