Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a class is a Model in Laravel 5

I have this code in Laravel 5.2 that checks if a given db table name ($what) has its own Model :

public function manage($what) {

    $model = Str::studly(Str::singular($what));
    if (!is_subclass_of($model, 'Model')) {
        \App::abort(404);
    }

    /* [... other stuff ...] */
}

The problem is that is_subclass_of always fail, also when the model exist and it's a subclass of Model. I suppose it's a namespace problem, how can I fix it?

like image 546
g4b0 Avatar asked Nov 23 '16 14:11

g4b0


2 Answers

You can check if your object is an instance of a model with instanceof:

$article = new \App\Article();

if ($article instanceof \Illuminate\Database\Eloquent\Model) {
like image 153
Alexey Mezenin Avatar answered Sep 28 '22 09:09

Alexey Mezenin


You may need the full namespace. When I do get_parent_class() on one of my models, it returns Illuminate\Database\Eloquent\Model. So use this instead:

$model = 'App\\' . Str::studly(Str::singular($what));
if (!is_subclass_of($model, 'Illuminate\Database\Eloquent\Model')) {
like image 28
aynber Avatar answered Sep 28 '22 10:09

aynber