Laravel 5.2 Controller Namespace - laravel-5

how i can change my controller namespace from
namespace App\Http\Controller\Folder\MyController
to
namespace Folder\MyController
im new using laravel 5.2

you can change psr-4 in your composer.json file.
"psr-4": {
"YourProject\\": "app/"
}
so, your namespace will be namespace YourProject/Http/Controller. don't forget to autoload your composer. I assume this is you are looking for.

This is baked in to 5.2 artisan commands;
php artisan app:name MyApp
think you'll need to run php artisan dump-autoload afterwards.

You need to add this in your controller:
namespace App\Http\Controllers\Folder;
use App\Http\Controllers\Controller;
and add this in your route,
Route::group(['namespace'=>'Folder'], function () {
// place your MyController route here;
});

Try this :
1) run php artisan app:name YourNamespace
2) rename your app folder to YourNamespace
3) in your bootstrap folder create a file called application.php
4) paste this in there
class Application extends Illuminate\Foundation\Application {
protected $appBasePath = 'app';
public function __construct($basePath = null)
{
$this->registerBaseBindings();
$this->registerBaseServiceProviders();
$this->registerCoreContainerAliases();
if ($basePath) $this->setBasePath($basePath);
}
public function setAppPath($path) {
// store the path in the class only
$this->appBasePath = $path;
// set the path in the container (using this class's path to reset it)
return app()->__set('path', $this->path());
}
/**
* Get the path to the application "app" directory.
*
* #return string
*/
public function path()
{
return $this->basePath.DIRECTORY_SEPARATOR.$this->appBasePath;
}
}
5) save the file and open app.php
6) and replace your application bootstrap with the following
// load our local application
require __DIR__.'/application.php';
// instaniate our application
$app = new \Application(
realpath(__DIR__.'/../')
);
// set the path to match the namespace
$app->setAppPath('YourNamespace');
7) Save your app.php and that's it
Hope this help you.

Related

Passing Company Data to All controller in Laravel 6.x

I am building an app where each company have multiple users. And all users can upload documents/images/xls etc. I want to keep all company data in company separate folder. To complete this I am checking the company detail for every user and then upload data to company specific folder. Can I check company database once per user login and share user's company details to all controller and can easily access.
Use view composer in your AppServiceProvider
App\Providers\AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
view()->composer('*',function($view) {
if(auth()->user()) {
$comanyData = App\Company::where('user_id',auth()->user()->id);
$view->with('companyData', $companyData);
}
});
}
}
You can make the helper function to use in controllers or blades files.
Let’s create a helper!
Create a simple PHP file.
Create Helper.php inside the app directory or wherever directory you want.
<?php
/**
* get company data
*
*/
function companyData()
{
// Create logic of company data
// return company data
}
Autoload Composer
After we created our helper, Laravel won’t recognize our file so we need to register the helper file to our composer.json. Add File array inside the autoload section. It may look like this:
"autoload": {
"classmap": ["database"],
"psr-4": {"App\\": "app/"},
"files" : ["app/Helper.php"]
}
Then don’t forget to run
composer dumpautoload
Using helper function
Our helper is autoloaded now, so we should be able to use our helper immediately on different controllers. Just call our function in any class
$companyData = companyData();
or in blade view
{{ companyData() }}
Let me know if you are facing an issue.
Below is how to share a variable with your entire application via the AppServiceProvider, You can also do this inside of your base controller in the construct method.
File: App\Providers\AppServiceProvider.php
<?php
namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
View::share('key', 'value');
}
}
You can then access $key inside of any view.

Laravel 5.5 Package Commands Won't Register

I have a package for Laravel 5.5 and in the CommandsServiceProvider boot() method, I have:
if($this->app->runningInConsole()){
$this->commands([
MyCommandClass:class,
]);
}
Then, my MyCommandClass looks like:
<?php
namespace Testing\Commands;
use Illuminate\Console\Command;
class MyCommandClass extends Command
{
protected $signature = "execute:test";
protected $description = "Description of the command";
public function __construct()
{
parent::__construct();
}
public function handle()
{
$this->info('Command Executed');
}
}
The issue is that Artisan does not list the command when I run php artisan and when I try to run the command with php artisan execute:test it tells me the command is not defined.
What am I missing here? I followed the documentation for registering package commands in Laravel 5.5
It would appear that the Auto discovery only works when pulling a package from a Git Repo via Composer. When developing a package, the composer files within the package do not seem to auto load.

Laravel 5.2 - ServiceProvider boot not working

Trying to use service provider to set a variables throughout all views pages that #extends('layouts.app') but not working, first I show the codes below.
AppServiceProvider
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Using class based composers...
view()->composer('layouts.app', function($view){
$view->with('current_user', Auth::user());
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
}
When I visit the page that calls {{$current_user}}, it shows the following error
ErrorException in 5a5612347179ad88a6d4ebacc5d911a184c1b4ed.php line 14:
Undefined variable: current_user (View: C:\xampp\htdocs\soyegg\resources\views\shops\edit\showroom.blade.php)
Went through a several questions solved in the website and checked the followings but still failed:
1. AppServiceProvider is in config.app (default by Laravel 5.2)
2. php artisan clear-compiled
3. php artisan optimize
4. check whether there is compiled.php and try to clear it mannually but there is in neither storage/framework nor vendor.
Please help!
I think your ServiceProvider is working fine, you only need to change the way you passing data to the view. I've tested it myself and I can confirm that passing data to a view which later will be included with #extends() won't work. Instead you can use another methods:
view()->share('current_user', Auth::user());
Or using wildcard:
view()->composer('*', function ($view) {
$view->with('current_user', Auth::user());
});
// wildcard with prefix
view()->composer('prefix.*', function ($view) {
$view->with('current_user', Auth::user());
});

Laravel: Controller does not exist

I added new controller in /app/controllers/admin/ folder and added the route in /app/routes.php file as well. Then i run the following command to autoload them
php artisan dump-autoload
I got the following error
Mcrypt PHP extension required.
I followed instruction given at https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql and able to resolve the mcrypt issue.
After that i run the php artisan dump-autoload command but still getting following error
{"error":{"type":"ReflectionException","message":"Class CoursesController does not exist","file":"\/var\/www\/html\/vendor\/laravel\/framework\/src\/Illuminate\/Container\/Container.php","line":504}}
Here is code of my routes.php file
Route::group(array('before' => 'adminauth', 'except' => array('/admin/login', '/admin/logout')), function() {
Route::resource('/admin/courses', 'CoursesController');
Route::resource('/admin/teachers', 'TeachersController');
Route::resource('/admin/subjects', 'SubjectsController');
});
Here is code of CoursesController.php file
<?php
class CoursesController extends BaseController
{
public function index()
{
$courses = Course::where('is_deleted', 0)->get();
return View::make('admin.courses.index', compact('courses'));
}
public function create()
{
return View::make('admin.courses.create');
}
public function store()
{
$validator = Validator::make($data = Input::all(), Course::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
Course::create($data);
return Response::json(array('message'=>'Course created successfully','status'=>'success'));
}
}
public function edit($id)
{
$course = Course::find($id);
return View::make('admin.courses.edit', compact('course'));
}
public function update($id)
{
$course = Course::findOrFail($id);
$validator = Validator::make($data = Input::all(), Course::editRules($id));
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
$course->update($data);
return Response::json(array('message'=>'Course updated successfully','status'=>'success'));
}
}
public function destroy($id)
{
Course::findOrFail($id)->update(array('is_deleted' => '1'));
return Response::json(array('message'=>'Course deleted successfully','status'=>'success'));
}
}
Did you add autoload classmap to composer.json file?
Open your composer.json file and add
"autoload": {
"classmap": [
"app/controllers/admin",
]
}
if you add folders inside controllers, you need to add it to composer.json file. Then run
composer dumpautoload
OR ALTERNATIVE
go to app/start/global.php and add
ClassLoader::addDirectories(array(
app_path().'/controllers/admin',
));
2021 answer (Laravel 8.5)
In your controller;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login(Request $request){
return "login";
}
}
In your routes;
use App\Http\Controllers\AuthController;
Route::post('/login', [AuthController::class, 'login']);
Doc = https://laravel.com/docs/8.x/routing#the-default-route-files
In my case, in the top of my controller code i add this line :
namespace App\Http\Controllers\CustomFolder\ControllerClassName;
and my problem is solved
We can create controller via command line.
php artisan make:controller nameController --plain.
Before Laravel 5, make namespace is not available. Instead, this works
php artisan controller:make nameController
Execute your command inside your project directory and then create your function.
Don't forget to do:
php artisan route:clear
In my case this was the solution when I got this error after making a route code change.
In my case, I had to change the route file from this:
Route::get('/','SessionController#accessSessionData');
to this:
Route::get('/','App\Http\Controllers\SessionController#accessSessionData');
then clearing the cache with this:
php artisan route:clear
made things work.
A bit late but in my experience adding this to the RouteServiceProvider.php solves the problem
protected $namespace = 'App\Http\Controllers';
I think your problem has already been fixed. But this is what did.
Structure
Http
.Auth
.CustomControllerFolder
-> CustomController.php
to get this working
in your route file make sure you use the correct name space
for eg:
Route::group(['namespace'=>'CustomControllerFolder','prefix'=>'prefix'],
function() {
//define your route here
}
Also dont forget to use namespace App\Http\Controllers\CustomControllerFolder in your controller.
That should fix the issue.
Thanks
I just had this issue because I renamed a file from EmployeeRequestContoller to EmployeeRequestsContoller, but when I renamed it I missed the .php extension!
When I reran php artisan make:controller EmployeeRequestsContoller just to be sure I wasn't going crazy and the file showed up I could clearly see the mistake:
/EmployeeRequestsContoller
/EmployeeRequestsContoller.php
Make sure you have the extension if you've renamed!
I use Laravel 9 this is the way we should use controllers
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Sometimes we are missing namespace App\Http\Controllers; on top of our controller code.
In my case, I have several backup files of admin and home controllers renamed with different dates and we ran a composer update on top of it and it gave us an error
after I removed the other older controller files and re-ran the composer update fixed my issue.
- Clue - composer update command gave us a warning.
Generating optimized autoload files
Warning: Ambiguous class resolution, "App\Http\Controllers\HomeController" was found in both "app/core/app/Http/Controllers/HomeController(25-OCT).php" and "app/core/app/Http/Controllers/HomeController.php", the first will be used.
Warning: Ambiguous class resolution, "App\Http\Controllers\AdminController" was found in both "app/core/app/Http/Controllers/AdminController(25-OCT).php" and "app/core/app/Http/Controllers/AdminController.php", the first will be used.
Use full namespace inside web.php
Route::resource('myusers','App\Http\Controllers\MyUserController');

global variable for all controller and views

In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following
public function __construct()
{
// Fetch the Site Settings object
$site_settings = Setting::all();
View::share('site_settings', $site_settings);
}
Now i want to access $site_settings. in all other controllers and views so that i don't need to write the same code again and again, so anybody please tell me the solution or any other way so i can fetch the data from the table once and use it in all controllers and view.
Okay, I'm going to completely ignore the ridiculous amount of over engineering and assumptions that the other answers are rife with, and go with the simple option.
If you're okay for there to be a single database call during each request, then the method is simple, alarmingly so:
class BaseController extends \Controller
{
protected $site_settings;
public function __construct()
{
// Fetch the Site Settings object
$this->site_settings = Setting::all();
View::share('site_settings', $this->site_settings);
}
}
Now providing that all of your controllers extend this BaseController, they can just do $this->site_settings.
If you wish to limit the amount of queries across multiple requests, you could use a caching solution as previously provided, but based on your question, the simple answer is a class property.
At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):
// You can keep this in your filters.php file
App::before(function($request) {
App::singleton('site_settings', function(){
return Setting::all();
});
// If you use this line of code then it'll be available in any view
// as $site_settings but you may also use app('site_settings') as well
View::share('site_settings', app('site_settings'));
});
To get the same data in any controller you may use:
$site_settings = app('site_settings');
There are many ways, just use one or another, which one you prefer but I'm using the Container.
Use the Config class:
Config::set('site_settings', $site_settings);
Config::get('site_settings');
http://laravel.com/docs/4.2/configuration
Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.
In Laravel, 5+ you can create a file in the config folder and create variables in that and use that across the app.
For instance, I want to store some information based on the site.
I create a file called site_vars.php,
which looks like this
<?php
return [
'supportEmail' => 'email#gmail.com',
'adminEmail' => 'admin#sitename.com'
];
Now in the routes, controller, views you can access it using
Config::get('site_vars.supportEmail')
In the views if I this
{{ Config::get('site_vars.supportEmail') }}
It will give email#gmail.com
Hope this helps.
EDiT-
You can also define vars in .env file and use them here.
That is the best way in my opinion as it gives you the flexibility to use values that you want on your local machine.
So, you can do something this in the array
'supportEmail' => env('SUPPORT_EMAIL', 'defaultmail#gmail.com')
Important - After you do this, don't forget to do this on production env
php artisan config:cache
In case, there's still some problem, then you can do this (usually it would never happen but still if it ever happens)
php artisan cache:clear
php artisan config:cache
In your local env, always do this after this adding it
php artisan config:clear
It's always a good practice not to cache config vars in local. in case, it was cached, this would remove the cache and would load the new changes.
I see, that this is still needed for 5.4+ and I just had the same problem, but none of the answers were clean enough, so I tried to accomplish the availability with ServiceProviders. Here is what i did:
Created the Provider SettingsServiceProvider
php artisan make:provider SettingsServiceProvider
Created the Model i needed (GlobalSettings)
php artisan make:model GlobalSettings
Edited the generated register method in \App\Providers\SettingsServiceProvider. As you can see, I retrieve my settings using the eloquent model for it with Setting::all().
public function register()
{
$this->app->singleton('App\GlobalSettings', function ($app) {
return new GlobalSettings(Setting::all());
});
}
Defined some useful parameters and methods (including the constructor with the needed Collection parameter) in GlobalSettings
class GlobalSettings extends Model
{
protected $settings;
protected $keyValuePair;
public function __construct(Collection $settings)
{
$this->settings = $settings;
foreach ($settings as $setting){
$this->keyValuePair[$setting->key] = $setting->value;
}
}
public function has(string $key){ /* check key exists */ }
public function contains(string $key){ /* check value exists */ }
public function get(string $key){ /* get by key */ }
}
At last I registered the provider in config/app.php
'providers' => [
// [...]
App\Providers\SettingsServiceProvider::class
]
After clearing the config cache with php artisan config:cache you can use your singleton as follows.
$foo = app(App\GlobalSettings::class);
echo $foo->has("company") ? $foo->get("company") : "Stack Exchange Inc.";
You can read more about service containers and service providers in Laravel Docs > Service Container and Laravel Docs > Service Providers.
This is my first answer and I had not much time to write it down, so the formatting ist a bit spacey, but I hope you get everything.
I forgot to include the boot method of SettingsServiceProvider, to make the settings variable global available in views, so here you go:
public function boot(GlobalSettings $settinsInstance)
{
View::share('globalsettings', $settinsInstance);
}
Before the boot methods are called all providers have been registered, so we can just use our GlobalSettings instance as parameter, so it can be injected by Laravel.
In blade template:
{{ $globalsettings->get("company") }}
View::share('site_settings', $site_settings);
Add to
app->Providers->AppServiceProvider file boot method
it's global variable.
Most popular answers here with BaseController didn't worked for me on Laravel 5.4, but they have worked on 5.3. No idea why.
I have found a way which works on Laravel 5.4 and gives variables even for views which are skipping controllers. And, of course, you can get variables from the database.
add in your app/Providers/AppServiceProvider.php
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// Using view composer to set following variables globally
view()->composer('*',function($view) {
$view->with('user', Auth::user());
$view->with('social', Social::all());
// if you need to access in controller and views:
Config::set('something', $something);
});
}
}
credit: http://laraveldaily.com/global-variables-in-base-controller/
In Laravel 5+, to set a variable just once and access it 'globally', I find it easiest to just add it as an attribute to the Request:
$request->attributes->add(['myVar' => $myVar]);
Then you can access it from any of your controllers using:
$myVar = $request->get('myVar');
and from any of your blades using:
{{ Request::get('myVar') }}
In Laravel 5.1 I needed a global variable populated with model data accessible in all views.
I followed a similar approach to ollieread's answer and was able to use my variable ($notifications) in any view.
My controller location: /app/Http/Controllers/Controller.php
<?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;
use App\Models\Main as MainModel;
use View;
abstract class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct() {
$oMainM = new MainModel;
$notifications = $oMainM->get_notifications();
View::share('notifications', $notifications);
}
}
My model location: /app/Models/Main.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use DB;
class Main extends Model
{
public function get_notifications() {...
I have found a better way which works on Laravel 5.5 and makes variables accessible by views. And you can retrieve data from the database, do your logic by importing your Model just as you would in your controller.
The "*" means you are referencing all views, if you research more you can choose views to affect.
add in your app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\ServiceProvider;
use App\Setting;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// Fetch the Site Settings object
view()->composer('*', function(View $view) {
$site_settings = Setting::all();
$view->with('site_settings', $site_settings);
});
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
}
}
If you are worried about repeated database access, make sure that you have some kind of caching built into your method so that database calls are only made once per page request.
Something like (simplified example):
class Settings {
static protected $all;
static public function cachedAll() {
if (empty(self::$all)) {
self::$all = self::all();
}
return self::$all;
}
}
Then you would access Settings::cachedAll() instead of all() and this would only make one database call per page request. Subsequent calls will use the already-retrieved contents cached in the class variable.
The above example is super simple, and uses an in-memory cache so it only lasts for the single request. If you wanted to, you could use Laravel's caching (using Redis or Memcached) to persist your settings across multiple requests. You can read more about the very simple caching options here:
http://laravel.com/docs/cache
For example you could add a method to your Settings model that looks like:
static public function getSettings() {
$settings = Cache::remember('settings', 60, function() {
return Settings::all();
});
return $settings;
}
This would only make a database call every 60 minutes otherwise it would return the cached value whenever you call Settings::getSettings().
You can also use Laravel helper which I'm using.
Just create Helpers folder under App folder
then add the following code:
namespace App\Helpers;
Use SettingModel;
class SiteHelper
{
public static function settings()
{
if(null !== session('settings')){
$settings = session('settings');
}else{
$settings = SettingModel::all();
session(['settings' => $settings]);
}
return $settings;
}
}
then add it on you config > app.php under alliases
'aliases' => [
....
'Site' => App\Helpers\SiteHelper::class,
]
1. To Use in Controller
use Site;
class SettingsController extends Controller
{
public function index()
{
$settings = Site::settings();
return $settings;
}
}
2. To Use in View:
Site::settings()
A global variable for using in controllers; you can set in AppServiceProvider like this :
public function boot()
{
$company=DB::table('company')->where('id',1)->first();
config(['yourconfig.company' => $company]);
}
usage
config('yourconfig.company');
using middlwares
1- create middlware with any name
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\View;
class GlobalData
{
public function handle($request, Closure $next)
{
// edit this section and share what do you want
$site_settings = Setting::all();
View::share('site_settings', $site_settings);
return $next($request);
}
}
2- register your middleware in Kernal.php
protected $routeMiddleware = [
.
...
'globaldata' => GlobalData::class,
]
3-now group your routes with globaldata middleware
Route::group(['middleware' => ['globaldata']], function () {
// add routes that need to site_settings
}
In file - \vendor\autoload.php, define your gobals variable as follows, should be in the topmost line.
$global_variable = "Some value";//the global variable
Access that global variable anywhere as :-
$GLOBALS['global_variable'];
Enjoy :)
I know I am super late to the party, but this was the easiest way I found.
In app/Providers/AppServiceProvider.php, add your variables in the boot method. Here I am retrieving all countries from the DB:
public function boot()
{
// Global variables
view()->composer('*',function($view) {
$view->with('countries', Country::all());
});
}
There are two options:
Create a php class file inside app/libraries/YourClassFile.php
a. Any function you create in it would be easily accessible in all the views and controllers.
b. If it is a static function you can easily access it by the class name.
c. Make sure you inclued "app/libraries" in autoload classmap in composer file.
In app/config/app.php create a variable and you can reference the same using
Config::get('variable_name');
Hope this helps.
Edit 1:
Example for my 1st point:
// app/libraries/DefaultFunctions.php
class DefaultFunctions{
public static function getSomeValue(){
// Fetch the Site Settings object
$site_settings = Setting::all();
return $site_settings;
}
}
//composer.json
"autoload": {
"classmap": [
..
..
..
"app/libraries" // add the libraries to access globaly.
]
}
//YourController.php
$default_functions = new DefaultFunctions();
$default_functions->getSomeValue();

Resources