Laravel - 动态加载模型和返回视图失败

I'm trying to dynamically load models based on what is being passed to it.

    class MyController extends Controller{
        $modelClass = "";
        public function __construct(){
            $this->setModel($modelName);
            }
        public function index(){
          $this->data['rows'] = $this->modelClass::all();
          return view('index', $this->data);
        }
        protected function setModel($modelName){
         if(!class_exists('\App\Models\\'.ucfirst($modelName)) || empty($modelName))
        {
            return view('page500');
        }else{
            $this->modelClass = '\App\Models\\'.ucfirst($modelName);
        }
        }
       }

I kept getting the error message "FatalThrowableError Class '' not found". I expect laravel to stop execution once a view have been returned but the execution isn't loading the page500 view and isn't stopping the execution.

Your setModel function returns a view to it's callee function, __construct. And that's all it does.

To immediately raise certain error - use abort function with error code as argument:

if(!class_exists('\App\Models\\'.ucfirst($modelName)) || empty($modelName))
{
     abort(500);
}

To modify error page layout - follow this instruction. Or simply create file resources/views/errors/500.blade.php.