Reputation: 7895
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
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
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
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
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