Home > front end >  inheritance i laravel :Class name must be a valid object or a string
inheritance i laravel :Class name must be a valid object or a string

Time:01-13

this is my parent class which is a user class that has the main crud operations

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Repositories\UserRepository;    //<----------- Here


class UserController extends Controller
{
    protected $model;



    public function index()
    {
        $users = $this->model::all();
        return view('users.index', compact('users'));
    }

}

this is my child class which is one of my user roles , it have the same crud operation but it need some more functinality

<?php

namespace App\Http\Controllers;
use App\Models\Teacher;
use App\Http\Controllers\UserController;

class TeacherController extends UserController
{

    public function __construct()
    {
        $this->model = Teacher::class;
    }
}

when I try to access the route i get this error : Class name must be a valid object or a string

at :

        $users = $this->model::all();

CodePudding user response:

will it seems my laravel project used an old cached routes , just run

 php artisan route:clear

from time to time before debugging anything

CodePudding user response:

Here the problem is, Your parent class cannot your model because your index() method of UserController is initialized before __construct() method of the TeacherController.

It could be more easier to guide if you have mentioned the route too. However, You may have called Usercontroller@index directly from route, if that is the case then, you have to declare your model on the constructor of Usercontroller or call TeacherController@index instead of Usercontroller.

  • Related