Laravel 5.5 - Class Custom BaseController not found but exists - php

Laravel 5.5 Custom BaseController not found even though it exists. Have checked the other questions on StackOverflow regarding the BaseController not found but they are referring to the default BaseController which isn't the same in mine case.
Here is my implementation
Controller.php
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as CheckController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends CheckController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
Custom BaseController (BaseController.php)
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
/**
* Setup the layout used by the controller.
*
* #return void
*/
public $data = array();
public function __construct()
{
if (Sentinel::check()) {
// User is not logged in, or is not activated
$this->data['admin'] = Sentinel::getUser();
}
}
protected function setupLayout()
{
if (!is_null($this->layout)) {
$this->layout = View::make($this->layout);
}
}
}
Extending a class named HomeCtontroller to Custom BaseController
class HomeController extends BaseController {
protected $layout = 'master';
public function main()
{
...
}
}
And then it gives the following error
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)
Class 'BaseController' not found
Would appreciate any sort of pointers.

I believe you haven't included full namespaces.
Make sure in BaseController you have:
namespace App\Http\Controllers;
and in HomeController make sure you are using:
use App\Http\Controllers\BaseController;
all those controllers should be located in app/Http/Controllers directory.
If you are sure you have valid directories and namespaces run composer dump-autoload in console

Related

laravel public variable for different controllers

I want to set a public variable so I can use it in different controllers. I tried this but it is not successful.
class HomeController extends Controller
{
public $TravelId;
public function __construct()
{
$this->TravelId=0;
}
}
then I used the same variable in another contorller
class HomeController extends Controller
{
public function index($cus_id)
{
//unique key for each user
$this->TravelId = $cus_id;
}
}
All your controllers extend App\Http\Controllers\Controller class by default, so you can add a property on this class and access it on all your controllers:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
/**
* Your static property
*/
public static $travelId;
}
Then you can access it on another controller:
self::$travelId = $cus_id;

Laravel Class 'App\Http\Controllers\Controller' not found

I am new to Laravel and I am trying to fix this error. Controller.php exists in App\Http\Controllers\. I have tried composer dump-autoload and it did not fix it.
I have read that I would need to use artisan to give name to my app. Then it would change namespace from App\ to my app name. Should I do that?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Html\FormBuilder;
use DB;
use App\Http\Controllers\Controller;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
public function insertform()
{
return view('home');
}
public function insertMeasurement(Request $request) {
$neck = $request->input('neck');
$arm_length = $request->input('arm_length');
$chest = $request->input('chest');
$stomach = $request->input('stomach');
$seat = $request->input('seat');
$shirt_length = $request->input('shirt_length');
$shoulder = $request->input('shoulder');
$arm = $request->input('arm');
$bicep = $request->input('bicep');
$wrist = $request->input('wrist');
$data=array("neck"=>$neck,"arm_length"=>$arm_length,"chest"=>$chest,"stomach"=>$stomach,"seat"=>$seat,
"shirt_length"=>$shirt_length,"shoulder"=>$shoulder,"arm"=>$arm,"bicep"=>$bicep,"wrist"=>$wrist);
DB::table('measurements')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Try composer dump-autoload command once.
Edit : Remove this line class HomeController extends Controller
and replace it with class HomeController extends \App\Http\Controllers\Controller
OR
class HomeController extends App\Http\Controllers\Controller
there is no need for this use App\Http\Controllers\Controller; take it off, your controller should be working fine.
Error can also occur if App/Http/Controllers/ folder does not have Controller.php file.
Make sure file exists.

Should I use Laravel Middleware?

I have a Laravel app that requires getting some config vars that need to be used by most of my controllers.
Therefore it seems like this would be the perfect time to use middleware.
Is this the correct use of middleware? and if so, once the middleware gets the config vars, is it best practice to add these to the request object so they can be accessed by my controller?
Thanks to any responders.
J
Not, definitely!
Actually (based on you've written), the best way to go is creating an application service and registering this service on Service Container - App\Providers\AppServiceProvider (in app/Providers/AppServiceProvider.php).
Something like this:
<?php
# The Config Service:
namespace App\Services;
/**
* Config Manager
*/
class Config
{
/** #var SomeDependency */
protected $dependency;
public function __construct(SomeDependency $dependency)
{
$this->dependency = $dependency;
}
public function getVar($var)
{
// ...
}
}
In your Service Provider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
//...
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->registerConfigManager();
}
public function registerConfigManager()
{
$this->app->singleton('config_service', function ($app) {
return new \App\Services\Config(new \SomeNamespace\SomeDependency);
});
}
//...
}
And now you can to access the service container via app(), like this:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class MyController extends Controller
{
public function index(Request $request)
{
app('config_service')->getVar('key');
//...
}
}
IMO, middlewares are made for pre-processing requests, restrict user access, and other security related.
I would simply load the configuration in the main Controller class and use it in the extending controllers.
For example:
base controller
namespace App\Http\Controllers;
uses goes here ...;
class Controller extends BaseController
{
protected $configs = [];
public function __construct() {
$this->loadConfigs();
}
protected function loadConfigs()
{
//read configuration files or tables in database
//and put the values into '$this->configs';
}
}
user controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class User extends Controller
{
public function index()
{
echo $this->configs['toolbar.color']; //just an example
}
}

Error Illuminate Database Eloquent Not Found

In the Controller when i tried to call a function from a model it Through Exception
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
Class 'Illuminate\Database\Eloquent' not found
the controller is simple and i used to create name space to manage sub directories controllers and model
<?php
namespace Manage ;
use Illuminate\Support\Facades\View;
use Illuminate\Routing\Controller;
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* #return void
*/
protected $layout = 'manage.layouts.master';
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout)->with(Dashboard::all());
}
}
}
and model
<?php
namespace Manage ;
use Illuminate\Database\Eloquent;
class Dashboard extends Eloquent{
protected $table = 'admin_dashboard_sidebar';
//put your code here
}
The class is Model:
use Illuminate\Database\Eloquent\Model as Eloquent;
or just
use Eloquent;
This last one is an alias to the class you can find in your app/config/app.php.
use Illuminate\Database\Eloquent\Model;
class Dashboard extends Model{
}

global variable in laravel

In PHP, I used to define some variables in my header.php and use them in all my pages. How can I have something like that in Laravel?
I am not talking about View::share('xx', 'xx' );
Assume I want to have a variable which holds a number in it and I need this number inside all my controllers to calculate something.
Sounds like a good candidate for a configuration file.
Create a new one, let's call it calculations.php:
Laravel ~4ish:
app
config
calculations.php
Laravel 5,6,7+:
config
calculations.php
Then put stuff in the new config file:
<?php return [ 'some_key' => 42 ];
Then retrieve the config in your code somewhere (note the file name becomes a "namespace" of sorts for the config item):
echo Config::get('calculations.some_key'); // 42 in Laravel ~4
echo config('calculations.some_key'); // 42 in Laravel ~5,6,7+
Set a property on the BaseController, which should be located in your controllers directory.
Your controllers should extend the BaseController class and thus inherit its properties.
You could use View Composers
And instead of using the boot method described in the docs you could use:
public function boot()
{
// Using class based composers...
view()->composer(
'*', 'App\Http\ViewComposers\ProfileComposer'
);
// Using Closure based composers...
view()->composer('*', function ($view) {
});
}
That would render whatever variables you declare with
$view->with('yourVariableName', 'yourVariableValue');
to all the views in your app.
Here is a full example of how I used this in one of my projects.
app/Providers/ComposerServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot()
{
view()->composer(
'*', 'App\Http\ViewComposers\UserComposer'
);
}
/**
* Register the application services.
*
* #return void
*/
public function register()
{
//
}
}
app/Http/ViewComposers/UserComposer.php
<?php
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
use Illuminate\Contracts\Auth\Guard;
class UserComposer
{
protected $auth;
public function __construct(Guard $auth)
{
// Dependencies automatically resolved by service container...
$this->auth = $auth;
}
public function compose(View $view)
{
$view->with('loggedInUser', $this->auth->user());
}
}
Just remember that because you declared a new service provider it needs to be included in the 'providers' array in config/app.php
You can define them in your app\Http\Controllers\Controller.php , for example:
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
public $test = 'something';
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
Then afterwards in all of your controllers, you can access this property by doing:
$this->test;

Categories