Laravel 4 Namespaces and Namespaces in Controllers

I was trying to arrange my controllers in Laravel 4 and added some nice namespaces to them

So I need routes like this Admin / Scientist-group And I wanted the controller to be in a subfolder called "admin"

So, I have a route file like this:

   //Admin Routes
Route::group(array('namespace' => 'admin'), function()
{
  Route::group(array('prefix' => 'admin'), function()
  {
    # Scholar Groups Controller
    Route::group(['before' => 'auth|adminGroup'], function()
    {
      Route::resource('scholar-groups', 'ScholarGroupController');
    });

  });
});

      

Then I added the namespace to my scientific profile GroupController which is in a subfolder named "admin"

    <?php namespace admin;
class ScholarGroupController extends \BaseController {

    /**
     * Display a listing of the resource.
     * GET /scholargroup
     *
     * @return Response
     */
    public function index()
    {
        $scholarGroups = ScholarGroup::paginate(10);
        return View::make('scholar_groups.index',compact('scholarGroups'));
    }

      

But whenever I try to access my pointer action in the controller, I get this error.

Class 'admin\ScholarGroup' not found

      

So the namespaces affect the model namespace on the next line

$scholarGroups = ScholarGroup::paginate(10);

      

How to avoid namespace affecting this model class namespace?

+3


source to share


1 answer


Your controller is in a namespace admin

, and references to other classes from it will be in that namespace.

So, you need to refer to your model with the previous backslash (as with BaseController

):

<?php namespace admin;

class ScholarGroupController extends \BaseController
{
    public function index()
    {
        $scholarGroups = \ScholarGroup::paginate(10);

        return View::make('scholar_groups.index',compact('scholarGroups'));
    }
}

      

or import it above the class declaration like this:



<?php namespace admin;

use ScholarGroup;

class ScholarGroupController extends \BaseController
{
    public function index()
    {
        $scholarGroups = ScholarGroup::paginate(10);

        return View::make('scholar_groups.index',compact('scholarGroups'));
    }
}

      

Plus, you don't have to do it Route::group

twice. You can do it:

Route::group(array('prefix' => 'admin', 'namespace' => 'admin'), function() {
    // . . .
});

      

+2


source







All Articles