Jim Jim - 1 year ago 86
PHP Question

Laravel 5.2 Controller returning an object

I am having problems with a controller returning just an object. I have a tables types and in TypesController I want a function that will just return an array of types so I can use it in another controller so I wrote in TypesController:

public function getNavTypes()
$types = DB::table('v_itemtypes')->get();
return ($types);

I want to call this in another controller (authors) so I added the line

use App\Http\Controllers\TypeController;

And want to just call the object in my method to pass on to the view:

public function getAuthor($author_id)

$author = Author::where('id', $author_id)->first();
$navtypes = TypeController::getNavTypes;
return view('authors.edit',['author'=>$author, 'navtypes'=>$navtypes]);

but I am getting the following error:

FatalErrorException in AuthorController.php line 28: Undefined class constant 'getNavTypes'

Line 28 is

$navtypes = TypeController::getNavTypes;

As a newbie I am doing something wrong, but what?

Answer Source

You cannot call a function without instantiating its class except if the function is static. So either you change your function to static:

public static function getNavTypes()

Or you instantiate an object of the controller first:

$typeController = new TypeController();
$navtypes = $typeController->getNavTypes();

And ah btw since getNavTypes is a function, you need to add two brackets:


before its name when calling it. So change $navtypes = TypeController::getNavTypes; to $navtypes = TypeController::getNavTypes();

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download