Extend Laravel 5 Response Facade - php

I am getting a namespacing issue when trying to extend the Response facade in Laravel 5. I have created a new folder tree under the app directory called Extensions\Facades. In this folder I have a file called AjaxResponse.php which has the following contents:
<?php namespace App\Extensions\Facades;
use Illuminate\Support\Facades\Response;
class AjaxResponse extends Response{
public static function send($code,$body,$http_code=200){
parent::json( array(
'status'=>(string)$code,
'body' =>$body
) )->setStatusCode($http_code)->send();
exit();
}
}
I am registering this as a service provider in config/app.php like I understand I am supposed to:
providers=[
//..normal stuff
'App\Extensions\Facades\AjaxResponse',
]
And this is throwing the normal namespace error of class not found:
FatalErrorException in ProviderRepository.php line 150:
Class 'App\Extensions\Facades\AjaxResponse' not found
Can anyone shed any light on why the class is not found?

Go to project root folder and in the terminal type
composer dump-autoload
Everything should be fine then. When you create a new folder, composer does not know about it, so it can not autoload files from it, even if they are psr-4 namespaced.
EDIT Also you need to declare alias for your facade in config/app.php under aliases array, not the providers one:
'AjaxResponse' => 'App\Extensions\Facades\AjaxResponse',

Related

Laravel package development - Target class [ControllerName] does not exist

I'm following a tutorial on how to create laravel packages.
I'm using Laravel v8.42.1 (PHP v7.4.3) and jetstream package.
I'm stuck on creating a controller for my package, I always get following error when trying to connect to my url via the laraval app (<base-url/playground):
Target class [TestVendor\TestPackage\Http\Controllers\PlaygroundController] does not exist.
The TestVendor\TestPackage\src\routes.php is recognized by the main application:
use TestVendor\TestPackage\Http\Controllers\PlaygroundController;
use Illuminate\Support\Facades\Route;
Route::get('/playground', [PlaygroundController::class, 'index']);
And is loaded from my ServiceProvider class:
$this->loadViewsFrom(__DIR__.'/resources/views', 'playground');
loadRoutesFrom(__DIR__.'/routes.php');
My namespacing is also normally correctly written in the composer.json of my package:
"autoload": {
"psr-4": {
"TestVendor\\TestPackage\\": "src/"
}
},
And I have my PlaygroundController in src/Http/Controllers/PlaygroundController.php:
namespace TestVendor\TestPackage\Http\Controllers;
use Illuminate\Routing\Controller;
class PlaygroundController extends Controller
{
public function index()
{
return view('playground::hello');
}
}
The view is also in the right package.
I'm using https://github.com/Jeroen-G/laravel-packager to scaffold my packages.
Did multiple composer auto-load and composer updates.
It seems my controller is not recognized in the main application, I think somewhere my name spacing is not correct?
I already had a look at:
Target class controller does not exist - Laravel 8
Solution did not work
Target class does not exist. problem in laravel 8
Solution did not work
You have namespaced your controller as:
namespace TestVendor\TestPackage\Http\Controllers;
In the line above though you say:
And I have my PlaygroundController in src/Http/PlaygroundController.php:
Unless that is a typo, you need to add a Controllers directory underneath Http and put your PlaygroundController in there:
src/Http/Controllers/PlaygroundController.php
For psr-4 autoloading, your folder structure and namespaces should mimic each other.

Laravel File equivalent in Lumen

I can access the list of files in a directory in Laravel using this:
use File;
....
$files = File::files($path);
However, I get this error in lumen:
Class 'File' not found
Any idea how I can access list of files in a folder in lumen.
File is only avaiable in Laravel by default. Although you can still used it on Lumen Framework by doing the following.
Enable the facade in boostrap/app.php by uncommenting the following code.
$app->withFacades();
After that, you will be able to access the File class in any of your controller by adding it as:
use Illuminate\Http\File;
or you can use the Facade Class.
use Illuminate\Support\Facades\File;
Please do a composer dump-autoload to update autoload.

Laravel Custom Trait Not Found

I'm new to traits, but thought I'd give it a try. But, it doesn't seem to load.
I've created a trait within a folder under the Laravel app directory: app\Helpers called CheckPermsAgainstObjectTrait.php
Here is the trait code:
<?php
namespace App\Helpers;
trait CheckPermsAgainstObjectTrait {
function something{}
}
I try to use it in a controller as such:
<?php
namespace App\Http\Controllers;
use this&that;
use App\Helpers\CheckPermsAgainstObjectTrait;
class PolicyController extends Controller{
use CheckPermsAgainstObjectTrait;
}
Classes in that directory load fine. PHPStorm sees the trait fine. I've clear compiled aritsan and dumped autoload. I'm guessing there is something that Laravel doesn't like with the namespacing? I would hope I don't need to do any manual loading in composer -- but I'm having trouble finding any documentation to give me a hint as to what I'm screwing up.
The error:
FatalErrorException in PolicyController.php line 15:
Trait 'App\Helpers\CheckPermsAgainstObjectTrait' not found
Any thoughts?
Did you dump autoload files?
composer dump-autoload
The answer for me was that I had the wrong namespace at the top of my trait file due to working from a Laravel trait as an example. If your trait is in App/Traits/MyTrait.php then make sure your namespace is:
namespace App\Traits;
trait MyTrait
{
// ..
}
Then from the file that's including the trait:
use App\Traits\MyTrait;
class MyClass
{
use MyTrait;
// ..
}
No need to mess with config/app.php, composer.json or autoloading.
I had a very similar problem where I was getting the error Trait 'Tests\CreatesApplication' not found in '.../my_project/tests/TestCase.php' on line 9 while running tests with phpunit because I manually updated my Laravel project and must have missed some changes. This may also happen to anyone creating a trait or class in a unique namespace.
Anyways, #Devon 's comment on the original question pointed me in the right direction.
I was missing the required autoloader configuration in my composer.json file, so I checked what it should be for my version of Laravel (5.4 in this case) from the Laravel github repository.
In this case, I was not calling from a namespace within App\ (which was already in composer.json.)
Here's what I was missing from composer.json:
{
...,
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
...
}
Thanks goes to Devon! Hope this keeps someone else from pulling their hair out.
composer dumpautoload -o
this worked for me
This may happen sometime when your Trait filename is misspelled or incorrect as with the class name. Do check your file name is same as classname
This may happen sometime when your Trait filename is misspelled or incorrect as with the class name. Do check your file name is same as classname

Laravel 5.1 "ReflectionException in Container.php line 737:..class does not exist"

I'm sure that the solution to this problem is staring me right in the face, but unfortunately I can't seem to figure it out. I'm trying to add a route to my laravel 5.1 installation, and I'm getting the below error...
ReflectionException in Container.php line 737:
Class App\Http\Controllers\Tools\DashBoardController does not exist
I first edited the routes file to include the below...
(file: app\Http\routes.php)
Route::get('dashboard', 'Tools\DashBoard#index');
Then I created the "Tools" folder and "DashBoardController.php" file, and have it setup to look somewhat like the below...
(file: app\Http\Controllers\Tools\DashBoardController.php)
namespace App\Http\Controllers\Tools\DashBoard;
//...etc...//
class DashBoardController extends Controller { /* ..etc.. */ }
Is this all I have to do? I read that you could run "composer dumpautoload" in the terminal but unfortunately that didn't help.
I'm on a localhost XAMPP install w/PHP7 on Win7, if that's useful. Any help is greatly appreciated!
Your namespace declaration should look like namespace App\Http\Controllers\Tools and should not contain the filename or name of your class. Then you need to change your route to point to the name of your class Route::get('dashboard', 'Tools\DashBoardController#index');.
The way autoloaders and namespaces work in PHP and specifically in Laravel is that the namespace must reflect the directory structure and the class name must match its filename.
If you will have multiple routes using controllers from the same namespace, you will probably benefit from implementing route group namespaces.

Including my class in a Laravel 5 Project

I made a class in php with some helper methods that parse HTML files.
I'd like to use this class in my Laravel project, but I'm new to Laravel and it's not clear how to add a simple class to a Laravel 5 project.
Is this possible? Or do I need to go to all the trouble of creating a composer package for my class, hosting it somewhere, and then require it in my composer.json file. That seems like a lot of work for including a simple PHP class, and I'm hoping there's an easier way.
As it stands right now there's not a great/easy way to do this in Laravel 5 (possibly by design). The two approaches you can take are
Create a new class in the App namespace
By default Laravel 5.0 looks for App\ prefixed classes in the app/ folder, so something like this should work
#File: app/Helpers/Myclass.php
<?php
namespace App\Helpers;
class Myclass
{
}
and then create your class with
$object = new App\Helpers\Myclass;
This approach, however, relies on you creating classes in the App\ namespace, and there's some ambiguity around if the App\ namespace is owned by Laravel, or is owned by the developer of the application.
Create your own Namespace and Register as PSR-4 autoloader
A better, but more complicated, approach would be to create classes in your own namespace, and then tell Laravel about this namespace by registering a new PSR autoloader.
First, you'd create the class definition
#File: application-lib/Myclass.php
<?php
namespace Pulsestorm;
class Myclass
{
}
Notice we've created a new folder off the root folder to hold our classes named application-lib. You could name this folder anything you like, because in the next step, you're going to add a section to your composer.json file's autoloader section
#File: composer.json
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/",
"Pulsestorm\\": "application-lib/"
}
},
The section we've added is this
"Pulsestorm\\": "application-lib/"
The key to the object (Pulsestorm\) is your namespace. The value (application-lib) is the folder where composer should look for class definition files with the specified namespace.
Once you've added this to composer.json, you'll need to tell Composer to regenerate it's autoload cache files with the dumpautoload command
$ composer dumpautoload
Generating autoload files
After doing the above, you should be able to instantiate your class with
$object = new Pulsestorm\Myclass;
The "real" right way to do this would be to create a generic composer package for your helper class, and then require that composer package into your laravel project. That may, however, be more work than you care to take on for a simple library helper.
If your class is generic enough to use it in other projects, the best way is to release it as a package.
Here's how you create packages with Laravel 5: http://laravel.com/docs/5.0/packages

Categories