Intervention laravel 5 - php

I'm trying to install intervention. I run this command
composer require intervention/image
and composer.json is updated.
I add 'Image' => 'Intervention\Image\Facades\Image::class'in $aliases array and it's ok. Then i addIntervention\Image\ImageServiceProvider::class` in the $providers array and it didn't work.
This is what i obtain when type composer update
PHP Fatal error: Class 'Intervention\Image\ImageServiceProvider' not found in /home/vagrant/Code/laravel-basics/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 146
[Symfony\Component\Debug\Exception\FatalErrorException]
Class 'Intervention\Image\ImageServiceProvider' not found `
<?php
ProviderRepository.php
<?php
namespace Illuminate\Foundation;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Contracts\Foundation\Application as ApplicationContract;
class ProviderRepository
{
/**
* The application implementation.
*
* #var \Illuminate\Contracts\Foundation\Application
*/
protected $app;
/**
* The filesystem instance.
*
* #var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* The path to the manifest file.
*
* #var string
*/
protected $manifestPath;
/**
* Create a new service repository instance.
*
* #param \Illuminate\Contracts\Foundation\Application $app
* #param \Illuminate\Filesystem\Filesystem $files
* #param string $manifestPath
* #return void
*/
public function __construct(ApplicationContract $app, Filesystem $files, $manifestPath)
{
$this->app = $app;
$this->files = $files;
$this->manifestPath = $manifestPath;
}
/**
* Register the application service providers.
*
* #param array $providers
* #return void
*/
public function load(array $providers)
{
$manifest = $this->loadManifest();
// First we will load the service manifest, which contains information on all
// service providers registered with the application and which services it
// provides. This is used to know which services are "deferred" loaders.
if ($this->shouldRecompile($manifest, $providers)) {
$manifest = $this->compileManifest($providers);
}
// Next, we will register events to load the providers for each of the events
// that it has requested. This allows the service provider to defer itself
// while still getting automatically loaded when a certain event occurs.
foreach ($manifest['when'] as $provider => $events) {
$this->registerLoadEvents($provider, $events);
}
// We will go ahead and register all of the eagerly loaded providers with the
// application so their services can be registered with the application as
// a provided service. Then we will set the deferred service list on it.
foreach ($manifest['eager'] as $provider) {
$this->app->register($this->createProvider($provider));
}
$this->app->setDeferredServices($manifest['deferred']);
}
/**
* Register the load events for the given provider.
*
* #param string $provider
* #param array $events
* #return void
*/
protected function registerLoadEvents($provider, array $events)
{
if (count($events) < 1) {
return;
}
$app = $this->app;
$app->make('events')->listen($events, function () use ($app, $provider) {
$app->register($provider);
});
}
/**
* Compile the application manifest file.
*
* #param array $providers
* #return array
*/
protected function compileManifest($providers)
{
// The service manifest should contain a list of all of the providers for
// the application so we can compare it on each request to the service
// and determine if the manifest should be recompiled or is current.
$manifest = $this->freshManifest($providers);
foreach ($providers as $provider) {
$instance = $this->createProvider($provider);
// When recompiling the service manifest, we will spin through each of the
// providers and check if it's a deferred provider or not. If so we'll
// add it's provided services to the manifest and note the provider.
if ($instance->isDeferred()) {
foreach ($instance->provides() as $service) {
$manifest['deferred'][$service] = $provider;
}
$manifest['when'][$provider] = $instance->when();
}
// If the service providers are not deferred, we will simply add it to an
// array of eagerly loaded providers that will get registered on every
// request to this application instead of "lazy" loading every time.
else {
$manifest['eager'][] = $provider;
}
}
return $this->writeManifest($manifest);
}
/**
* Create a new provider instance.
*
* #param string $provider
* #return \Illuminate\Support\ServiceProvider
*/
public function createProvider($provider)
{
return new $provider($this->app);
}
/**
* Determine if the manifest should be compiled.
*
* #param array $manifest
* #param array $providers
* #return bool
*/
public function shouldRecompile($manifest, $providers)
{
return is_null($manifest) || $manifest['providers'] != $providers;
}
/**
* Load the service provider manifest JSON file.
*
* #return array
*/
public function loadManifest()
{
// The service manifest is a file containing a JSON representation of every
// service provided by the application and whether its provider is using
// deferred loading or should be eagerly loaded on each request to us.
if ($this->files->exists($this->manifestPath)) {
$manifest = json_decode($this->files->get($this->manifestPath), true);
return array_merge(['when' => []], $manifest);
}
}
/**
* Write the service manifest file to disk.
*
* #param array $manifest
* #return array
*/
public function writeManifest($manifest)
{
$this->files->put(
$this->manifestPath, json_encode($manifest, JSON_PRETTY_PRINT)
);
return $manifest;
}
/**
* Create a fresh service manifest data structure.
*
* #param array $providers
* #return array
*/
protected function freshManifest(array $providers)
{
return ['providers' => $providers, 'eager' => [], 'deferred' => []];
}
}
composer.json
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.1.*",
"intervention/image": "dev-master"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
"mockery/mockery": "0.9.*",
"phpunit/phpunit": "~4.0",
"phpspec/phpspec": "~2.1"
},
"autoload": {
"classmap": [
"database",
"app/Models"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"classmap": [
"tests/TestCase.php"
]
},
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-update-cmd": [
"php artisan clear-compiled",
"php artisan optimize"
],
"post-root-package-install": [
"php -r \"copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"php artisan key:generate"
]
},
"config": {
"preferred-install": "dist"
},
"require": {
"illuminate/html": "5.*"
},
"minimum-stability": "dev",
"prefer-stable": true
}

I would try removing ::class.
This setup works for me:
'providers' => [
'Intervention\Image\ImageServiceProvider',
],
'aliases' => [
'Image' => 'Intervention\Image\Facades\Image',
]

If you're using the PHP 5.5 ::class reference, then you shouldn't put it in quotes. Putting it in quotes makes it a string, and that's not what it is. It's just a static reference to the fully qualified class name.
So you either want to use this
'providers' => [
Intervention\Image\ImageServiceProvider::class,
],
'aliases' => [
'Image' => Intervention\Image\Facades\Image::class,
]
or this
'providers' => [
'Intervention\Image\ImageServiceProvider',
],
'aliases' => [
'Image' => 'Intervention\Image\Facades\Image',
]

Related

Symfony 3.3 Parse error: syntax error, unexpected ':', expecting ';' or '{' in c:\xampp\htdocs\myproject\path\to\AnnotationRegistry.php on line 50

I have downloaded and installed Symfony 3.3 and i work with php 7.2 . I started to follow a symfony tutorial, everything was fine but once I did the symfony update with the command "php ../composer.phar update" I had this error:
Parse error: error syntax, unexpected ':', expecting ';' or '{' in
C: \ wamp \ wamp64 \ www \ Symfony \ Vendor \ Doctrine \ Annotations \ lib \ Doctrine \ Common \ Annotations \ AnnotationRegistry.php
This is the content of composer.php :
{
"name": "cashexpress/symfony",
"license": "proprietary",
"type": "project",
"autoload": {
"psr-4": {
"": "src/"
},
"classmap": [
"app/AppKernel.php",
"app/AppCache.php"
]
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
},
"files": [
"vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php"
]
},
"require": {
"php": ">=5.5.9",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
"incenteev/composer-parameter-handler": "^2.0",
"sensio/distribution-bundle": "^5.0.19",
"sensio/framework-extra-bundle": "^3.0.2",
"symfony/monolog-bundle": "^3.1.0",
"symfony/polyfill-apcu": "^1.0",
"symfony/swiftmailer-bundle": "^2.3.10",
"symfony/symfony": "3.3.*",
"twig/twig": "^1.0||^2.0",
"doctrine/doctrine-fixtures-bundle": "~2.3"
},
"require-dev": {
"sensio/generator-bundle": "^3.0",
"symfony/phpunit-bridge": "^3.0"
},
"scripts": {
"symfony-scripts": [
"Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
],
"post-install-cmd": [
"#symfony-scripts"
],
"post-update-cmd": [
"#symfony-scripts"
]
},
"config": {
"sort-packages": true
},
"extra": {
"symfony-app-dir": "app",
"symfony-bin-dir": "bin",
"symfony-var-dir": "var",
"symfony-web-dir": "web",
"symfony-tests-dir": "tests",
"symfony-assets-install": "relative",
"incenteev-parameters": {
"file": "app/config/parameters.yml"
},
"branch-alias": null
} }
This is the content of AnnotationRegistry.php:
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\Common\Annotations;
final class AnnotationRegistry
{
/**
* A map of namespaces to use for autoloading purposes based on a PSR-0 convention.
*
* Contains the namespace as key and an array of directories as value. If the value is NULL
* the include path is used for checking for the corresponding file.
*
* This autoloading mechanism does not utilize the PHP autoloading but implements autoloading on its own.
*
* #var string[][]|string[]|null[]
*/
static private $autoloadNamespaces = [];
/**
* A map of autoloader callables.
*
* #var callable[]
*/
static private $loaders = [];
/**
* An array of classes which cannot be found
*
* #var null[] indexed by class name
*/
static private $failedToAutoload = [];
public static function reset() : void
{
self::$autoloadNamespaces = [];
self::$loaders = [];
self::$failedToAutoload = [];
}
/**
* Registers file.
*
* #deprecated this method is deprecated and will be removed in doctrine/annotations 2.0
* autoloading should be deferred to the globally registered autoloader by then. For now,
* use #example AnnotationRegistry::registerLoader('class_exists')
*/
public static function registerFile(string $file) : void
{
require_once $file;
}
/**
* Adds a namespace with one or many directories to look for files or null for the include path.
*
* Loading of this namespaces will be done with a PSR-0 namespace loading algorithm.
*
* #param string $namespace
* #param string|array|null $dirs
*
* #deprecated this method is deprecated and will be removed in doctrine/annotations 2.0
* autoloading should be deferred to the globally registered autoloader by then. For now,
* use #example AnnotationRegistry::registerLoader('class_exists')
*/
public static function registerAutoloadNamespace(string $namespace, $dirs = null) : void
{
self::$autoloadNamespaces[$namespace] = $dirs;
}
/**
* Registers multiple namespaces.
*
* Loading of this namespaces will be done with a PSR-0 namespace loading algorithm.
*
* #param string[][]|string[]|null[] $namespaces indexed by namespace name
*
* #deprecated this method is deprecated and will be removed in doctrine/annotations 2.0
* autoloading should be deferred to the globally registered autoloader by then. For now,
* use #example AnnotationRegistry::registerLoader('class_exists')
*/
public static function registerAutoloadNamespaces(array $namespaces) : void
{
self::$autoloadNamespaces = \array_merge(self::$autoloadNamespaces, $namespaces);
}
/**
* Registers an autoloading callable for annotations, much like spl_autoload_register().
*
* NOTE: These class loaders HAVE to be silent when a class was not found!
* IMPORTANT: Loaders have to return true if they loaded a class that could contain the searched annotation class.
*
* #deprecated this method is deprecated and will be removed in doctrine/annotations 2.0
* autoloading should be deferred to the globally registered autoloader by then. For now,
* use #example AnnotationRegistry::registerLoader('class_exists')
*/
public static function registerLoader(callable $callable) : void
{
// Reset our static cache now that we have a new loader to work with
self::$failedToAutoload = [];
self::$loaders[] = $callable;
}
/**
* Registers an autoloading callable for annotations, if it is not already registered
*
* #deprecated this method is deprecated and will be removed in doctrine/annotations 2.0
*/
public static function registerUniqueLoader(callable $callable) : void
{
if ( ! in_array($callable, self::$loaders, true) ) {
self::registerLoader($callable);
}
}
/**
* Autoloads an annotation class silently.
*/
public static function loadAnnotationClass(string $class) : bool
{
if (\class_exists($class, false)) {
return true;
}
if (\array_key_exists($class, self::$failedToAutoload)) {
return false;
}
foreach (self::$autoloadNamespaces AS $namespace => $dirs) {
if (\strpos($class, $namespace) === 0) {
$file = \str_replace('\\', \DIRECTORY_SEPARATOR, $class) . '.php';
if ($dirs === null) {
if ($path = stream_resolve_include_path($file)) {
require $path;
return true;
}
} else {
foreach((array) $dirs AS $dir) {
if (is_file($dir . \DIRECTORY_SEPARATOR . $file)) {
require $dir . \DIRECTORY_SEPARATOR . $file;
return true;
}
}
}
}
}
foreach (self::$loaders AS $loader) {
if ($loader($class) === true) {
return true;
}
}
self::$failedToAutoload[$class] = null;
return false;
}
}
I saw the other solutions proposed on stackoverflow but I did not find an answer to this error
 I do not know what to do now. I'm only new to Symfony. Help is badly needed.
composer update doctrine/annotations results :
[1]: https://i.stack.imgur.com/uIyWa.jpg
composer show doctrine/annotations results :
[1]: https://i.stack.imgur.com/NfjRH.jpg
Ensure that you are using php version >= 7.1
Also specify you PHP version in composer.json:
"config": {
"platform": {
"php": "7.2"
}
}
after that, run
composer update doctrine/annotations
Looks to me like your PHP version isn't 7.2, ensure the PHP version in the command line is also PHP 7.2 by running php -v. The error you're getting looks as it fails on the return types.

Adding currency picker to laravel

I want to have a drop-down in my navbar where I can select a currency and all the prices in my app convert to selected currency, I know I should use middle-ware for this matter but I don't know how to begin. I am using Fixer with laravel-swap as a package for exchange rates.
What I've done
I have made a middleware named it Currancy and it's content:
<?php
namespace App\Http\Middleware;
use Closure;
use Swap\Swap;
use Swap\Builder;
class Currancy
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Session::has('appcurrency') AND array_key_exists(Session::get('appcurrency'), Config::get('currencies'))) {
$currency = Session::get('appcurrency');
App::setLocale($currency);
}
else {
App::setLocale(Config::get('app.currency'));
}
return $next($request);
}
}
I also made a currencies.php in config folder:
<?php
return [
'IDR' => [
'name' => 'Indunesian Rupiah',
],
'USD' => [
'name' => 'U.S Dollar',
],
'EUR' => [
'name' => 'Euro',
],
];
I also added this to my config\app.php
'currency' => 'IDR',
in that case my default currency is IDR unless user select others.
PS: for my middleware and config file I've got the idea of language
translation and I don't have an idea how to join it to SWAP package in
order to work! :\
Questions
Is the way I try to handle currencies correct way?
What else should I do for the next step?
thanks.
App::setLocale() is for language purpose.
Do not use a middle-ware to set a session default value. It will bloat your route file. Use the view composer for output. https://laravel.com/docs/4.2/responses#view-composers
Run this command if you do not have a view composer provider:
php artisan make:provider ComposerServiceProvider
In "app/Providers/ComposerServiceProvider.php", in the "boot()" method
public function boot()
{
View::composer(array('header','footer'), function($view)
{
if (!currentCurrency()) {
setCurrency(config('app.currency'));
}
$view->with('currencies', config('currencies');
});
}
Define some helper functions.
To load a helper, use the autoload feature of the composer.
In "composer.json" in the "autoload" attribute tight, after the "psr-4" one:
it will load "app/Support/helpers.php" as an example.
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Support/helpers.php"
]
After changing "composer.json", regenerate the autoload file with the command:
composer dump-autoload
In "app/Support/helpers.php" (create it) add these functions:
<?php
if (!function_exists('currentCurrency')) {
/**
* #return string
*/
function currentCurrency(){
if (Session::has('appcurrency') AND array_key_exists(Session::get('appcurrency'), config('currencies'))) {
return Session::get('appcurrency');
}
return '';
}
}
if (!function_exists('setCurrency')) {
/**
* #param string $currency
* #return void
* #throws \Exception
*/
function setCurrency($currency){
if (array_key_exists($currency, config('currencies'))) {
Session::set('appcurrency', $currency);
} else {
throw new \Exception('not a valid currency');
}
}
}
If you need to set the locale to one of the currency, change the "setCurrency" method, since you only need to set the locale once per session.
/**
* #param string $currency
* #return void
* #throws \Exception
*/
function setCurrency($currency){
if (array_key_exists($currency, config('currencies'))) {
Session::set('appcurrency', $currency);
App::setLocale($currency);
} else {
throw new \Exception('not a valid currency');
}
}

Upgrade to Laravel 5.6 from 5.5 [duplicate]

I am trying to upgrade my Laravel 5.5 to 5.6. I have followed the instructions from the laravel website, yet I got this error:
Your requirements could not be resolved to an installable set of packages.
Problem 1
- The requested package laravel/framework 5.6.* is satisfiable by laravel/framework[5.6.x-dev] but these conflict with your requirements or minimum-stability.
So, I changed my composer.json file and added 2 lines: **"minimum-stability": "dev", "prefer-stable": true,** based on the first answer on this laracast discussion.
Everything seemed to be working just fine until I got another error:
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 6 updates, 0 removals
- Updating sebastian/diff (2.0.1 => 3.0.0): Downloading (100%)
- Updating phpunit/phpunit-mock-objects (5.0.6 => 6.0.0): Downloading (100%) - Updating phpunit/php-timer (1.0.9 => 2.0.0): Downloading (100%)
- Updating phpunit/php-token-stream (2.0.2 => 3.0.0): Downloading (100%) - Updating phpunit/php-code-coverage (5.3.0 => 6.0.1): Downloading (100%) - Updating phpunit/phpunit (6.5.6 => 7.0.0): Downloading (100%)
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> #php artisan package:discover
In trustedproxy.php line 66:
Undefined class constant 'HEADER_CLIENT_IP'
Script #php artisan package:discover handling the post-autoload-dump event returned with error code 1
The problem on line 66 is Illuminate\Http\Request::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',.
I have searched other posts on stackoverflow but still no luck. The last thing I tried was composer selfupdate and composer global update which was mentioned on the post composer dump-autoload not recognized command
Also, I cannot remove "minimum-stability": "dev","prefer-stable": true because if I do, then I will get the following error:
- Installation request for laravel/framework 5.6.* -> satisfiable by laravel/framework[5.6.x-dev].
- Removal request for laravel/framework == 5.6.9999999.9999999-dev
I have attached my composer.json file and trustedproxy.php respectively. Any help will be highly appreciated.
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"minimum-stability": "dev",
"prefer-stable": true,
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
"php": ">=7.1.3",
"fideloper/proxy": "~3.3",
"laravel/framework": "5.6.*",
"laravel/tinker": "~1.0"
},
"require-dev": {
"filp/whoops": "~2.0",
"fzaninotto/faker": "~1.4",
"mockery/mockery": "~1.0",
"phpunit/phpunit": "~7.0",
"symfony/thanks": "^1.0"
},
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"extra": {
"laravel": {
"dont-discover": [
]
}
},
"scripts": {
"post-root-package-install": [
"#php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"#php artisan key:generate"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover"
]
},
"config": {
"preferred-install": "dist",
"sort-packages": true,
"optimize-autoloader": true
}
}
trustedproxy.php (error in line 66--> Illuminate\Http\Request::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',)
<?php
return [
/*
* Set trusted proxy IP addresses.
*
* Both IPv4 and IPv6 addresses are
* supported, along with CIDR notation.
*
* The "*" character is syntactic sugar
* within TrustedProxy to trust any proxy
* that connects directly to your server,
* a requirement when you cannot know the address
* of your proxy (e.g. if using Rackspace balancers).
*
* The "**" character is syntactic sugar within
* TrustedProxy to trust not just any proxy that
* connects directly to your server, but also
* proxies that connect to those proxies, and all
* the way back until you reach the original source
* IP. It will mean that $request->getClientIp()
* always gets the originating client IP, no matter
* how many proxies that client's request has
* subsequently passed through.
*/
'proxies' => [
'192.168.1.10',
],
/*
* Or, to trust all proxies that connect
* directly to your server, uncomment this:
*/
# 'proxies' => '*',
/*
* Or, to trust ALL proxies, including those that
* are in a chain of forwarding, uncomment this:
*/
# 'proxies' => '**',
/*
* Default Header Names
*
* Change these if the proxy does
* not send the default header names.
*
* Note that headers such as X-Forwarded-For
* are transformed to HTTP_X_FORWARDED_FOR format.
*
* The following are Symfony defaults, found in
* \Symfony\Component\HttpFoundation\Request::$trustedHeaders
*
* You may optionally set headers to 'null' here if you'd like
* for them to be considered untrusted instead. Ex:
*
* Illuminate\Http\Request::HEADER_CLIENT_HOST => null,
*
* WARNING: If you're using AWS Elastic Load Balancing or Heroku,
* the FORWARDED and X_FORWARDED_HOST headers should be set to null
* as they are currently unsupported there.
*/
'headers' => [
(defined('Illuminate\Http\Request::HEADER_FORWARDED') ? Illuminate\Http\Request::HEADER_FORWARDED : 'forwarded') => 'FORWARDED',
Illuminate\Http\Request::HEADER_CLIENT_IP => 'X_FORWARDED_FOR',
Illuminate\Http\Request::HEADER_CLIENT_HOST => 'X_FORWARDED_HOST',
Illuminate\Http\Request::HEADER_CLIENT_PROTO => 'X_FORWARDED_PROTO',
Illuminate\Http\Request::HEADER_CLIENT_PORT => 'X_FORWARDED_PORT',
]
];
Illuminate\Http\Request file:
<?php
namespace Illuminate\Http;
use Closure;
use ArrayAccess;
use RuntimeException;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Contracts\Support\Arrayable;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
class Request extends SymfonyRequest implements Arrayable, ArrayAccess
{
use Concerns\InteractsWithContentTypes,
Concerns\InteractsWithFlashData,
Concerns\InteractsWithInput,
Macroable;
/**
* The decoded JSON content for the request.
*
* #var \Symfony\Component\HttpFoundation\ParameterBag|null
*/
protected $json;
/**
* All of the converted files for the request.
*
* #var array
*/
protected $convertedFiles;
/**
* The user resolver callback.
*
* #var \Closure
*/
protected $userResolver;
/**
* The route resolver callback.
*
* #var \Closure
*/
protected $routeResolver;
/**
* Create a new Illuminate HTTP request from server variables.
*
* #return static
*/
public static function capture()
{
static::enableHttpMethodParameterOverride();
return static::createFromBase(SymfonyRequest::createFromGlobals());
}
/**
* Return the Request instance.
*
* #return $this
*/
public function instance()
{
return $this;
}
/**
* Get the request method.
*
* #return string
*/
public function method()
{
return $this->getMethod();
}
/**
* Get the root URL for the application.
*
* #return string
*/
public function root()
{
return rtrim($this->getSchemeAndHttpHost().$this->getBaseUrl(), '/');
}
/**
* Get the URL (no query string) for the request.
*
* #return string
*/
public function url()
{
return rtrim(preg_replace('/\?.*/', '', $this->getUri()), '/');
}
/**
* Get the full URL for the request.
*
* #return string
*/
public function fullUrl()
{
$query = $this->getQueryString();
$question = $this->getBaseUrl().$this->getPathInfo() == '/' ? '/?' : '?';
return $query ? $this->url().$question.$query : $this->url();
}
/**
* Get the full URL for the request with the added query string parameters.
*
* #param array $query
* #return string
*/
public function fullUrlWithQuery(array $query)
{
$question = $this->getBaseUrl().$this->getPathInfo() == '/' ? '/?' : '?';
return count($this->query()) > 0
? $this->url().$question.http_build_query(array_merge($this->query(), $query))
: $this->fullUrl().$question.http_build_query($query);
}
/**
* Get the current path info for the request.
*
* #return string
*/
public function path()
{
$pattern = trim($this->getPathInfo(), '/');
return $pattern == '' ? '/' : $pattern;
}
/**
* Get the current decoded path info for the request.
*
* #return string
*/
public function decodedPath()
{
return rawurldecode($this->path());
}
/**
* Get a segment from the URI (1 based index).
*
* #param int $index
* #param string|null $default
* #return string|null
*/
public function segment($index, $default = null)
{
return Arr::get($this->segments(), $index - 1, $default);
}
/**
* Get all of the segments for the request path.
*
* #return array
*/
public function segments()
{
$segments = explode('/', $this->decodedPath());
return array_values(array_filter($segments, function ($value) {
return $value !== '';
}));
}
/**
* Determine if the current request URI matches a pattern.
*
* #param dynamic $patterns
* #return bool
*/
public function is(...$patterns)
{
foreach ($patterns as $pattern) {
if (Str::is($pattern, $this->decodedPath())) {
return true;
}
}
return false;
}
/**
* Determine if the route name matches a given pattern.
*
* #param dynamic $patterns
* #return bool
*/
public function routeIs(...$patterns)
{
return $this->route() && $this->route()->named(...$patterns);
}
/**
* Determine if the current request URL and query string matches a pattern.
*
* #param dynamic $patterns
* #return bool
*/
public function fullUrlIs(...$patterns)
{
$url = $this->fullUrl();
foreach ($patterns as $pattern) {
if (Str::is($pattern, $url)) {
return true;
}
}
return false;
}
/**
* Determine if the request is the result of an AJAX call.
*
* #return bool
*/
public function ajax()
{
return $this->isXmlHttpRequest();
}
/**
* Determine if the request is the result of an PJAX call.
*
* #return bool
*/
public function pjax()
{
return $this->headers->get('X-PJAX') == true;
}
/**
* Determine if the request is over HTTPS.
*
* #return bool
*/
public function secure()
{
return $this->isSecure();
}
/**
* Get the client IP address.
*
* #return string
*/
public function ip()
{
return $this->getClientIp();
}
/**
* Get the client IP addresses.
*
* #return array
*/
public function ips()
{
return $this->getClientIps();
}
/**
* Get the client user agent.
*
* #return string
*/
public function userAgent()
{
return $this->headers->get('User-Agent');
}
/**
* Merge new input into the current request's input array.
*
* #param array $input
* #return \Illuminate\Http\Request
*/
public function merge(array $input)
{
$this->getInputSource()->add($input);
return $this;
}
/**
* Replace the input for the current request.
*
* #param array $input
* #return \Illuminate\Http\Request
*/
public function replace(array $input)
{
$this->getInputSource()->replace($input);
return $this;
}
/**
* Get the JSON payload for the request.
*
* #param string $key
* #param mixed $default
* #return \Symfony\Component\HttpFoundation\ParameterBag|mixed
*/
public function json($key = null, $default = null)
{
if (! isset($this->json)) {
$this->json = new ParameterBag((array) json_decode($this->getContent(), true));
}
if (is_null($key)) {
return $this->json;
}
return data_get($this->json->all(), $key, $default);
}
/**
* Get the input source for the request.
*
* #return \Symfony\Component\HttpFoundation\ParameterBag
*/
protected function getInputSource()
{
if ($this->isJson()) {
return $this->json();
}
return $this->getRealMethod() == 'GET' ? $this->query : $this->request;
}
/**
* Create an Illuminate request from a Symfony instance.
*
* #param \Symfony\Component\HttpFoundation\Request $request
* #return \Illuminate\Http\Request
*/
public static function createFromBase(SymfonyRequest $request)
{
if ($request instanceof static) {
return $request;
}
$content = $request->content;
$request = (new static)->duplicate(
$request->query->all(), $request->request->all(), $request->attributes->all(),
$request->cookies->all(), $request->files->all(), $request->server->all()
);
$request->content = $content;
$request->request = $request->getInputSource();
return $request;
}
/**
* {#inheritdoc}
*/
public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
{
return parent::duplicate($query, $request, $attributes, $cookies, $this->filterFiles($files), $server);
}
/**
* Filter the given array of files, removing any empty values.
*
* #param mixed $files
* #return mixed
*/
protected function filterFiles($files)
{
if (! $files) {
return;
}
foreach ($files as $key => $file) {
if (is_array($file)) {
$files[$key] = $this->filterFiles($files[$key]);
}
if (empty($files[$key])) {
unset($files[$key]);
}
}
return $files;
}
/**
* Get the session associated with the request.
*
* #return \Illuminate\Session\Store
*
* #throws \RuntimeException
*/
public function session()
{
if (! $this->hasSession()) {
throw new RuntimeException('Session store not set on request.');
}
return $this->session;
}
/**
* Get the session associated with the request.
*
* #return \Illuminate\Session\Store|null
*/
public function getSession()
{
return $this->session;
}
/**
* Set the session instance on the request.
*
* #param \Illuminate\Contracts\Session\Session $session
* #return void
*/
public function setLaravelSession($session)
{
$this->session = $session;
}
/**
* Get the user making the request.
*
* #param string|null $guard
* #return mixed
*/
public function user($guard = null)
{
return call_user_func($this->getUserResolver(), $guard);
}
/**
* Get the route handling the request.
*
* #param string|null $param
*
* #return \Illuminate\Routing\Route|object|string
*/
public function route($param = null)
{
$route = call_user_func($this->getRouteResolver());
if (is_null($route) || is_null($param)) {
return $route;
}
return $route->parameter($param);
}
/**
* Get a unique fingerprint for the request / route / IP address.
*
* #return string
*
* #throws \RuntimeException
*/
public function fingerprint()
{
if (! $route = $this->route()) {
throw new RuntimeException('Unable to generate fingerprint. Route unavailable.');
}
return sha1(implode('|', array_merge(
$route->methods(), [$route->getDomain(), $route->uri(), $this->ip()]
)));
}
/**
* Set the JSON payload for the request.
*
* #param \Symfony\Component\HttpFoundation\ParameterBag $json
* #return $this
*/
public function setJson($json)
{
$this->json = $json;
return $this;
}
/**
* Get the user resolver callback.
*
* #return \Closure
*/
public function getUserResolver()
{
return $this->userResolver ?: function () {
//
};
}
/**
* Set the user resolver callback.
*
* #param \Closure $callback
* #return $this
*/
public function setUserResolver(Closure $callback)
{
$this->userResolver = $callback;
return $this;
}
/**
* Get the route resolver callback.
*
* #return \Closure
*/
public function getRouteResolver()
{
return $this->routeResolver ?: function () {
//
};
}
/**
* Set the route resolver callback.
*
* #param \Closure $callback
* #return $this
*/
public function setRouteResolver(Closure $callback)
{
$this->routeResolver = $callback;
return $this;
}
/**
* Get all of the input and files for the request.
*
* #return array
*/
public function toArray()
{
return $this->all();
}
/**
* Determine if the given offset exists.
*
* #param string $offset
* #return bool
*/
public function offsetExists($offset)
{
return array_key_exists(
$offset, $this->all() + $this->route()->parameters()
);
}
/**
* Get the value at the given offset.
*
* #param string $offset
* #return mixed
*/
public function offsetGet($offset)
{
return $this->__get($offset);
}
/**
* Set the value at the given offset.
*
* #param string $offset
* #param mixed $value
* #return void
*/
public function offsetSet($offset, $value)
{
$this->getInputSource()->set($offset, $value);
}
/**
* Remove the value at the given offset.
*
* #param string $offset
* #return void
*/
public function offsetUnset($offset)
{
$this->getInputSource()->remove($offset);
}
/**
* Check if an input element is set on the request.
*
* #param string $key
* #return bool
*/
public function __isset($key)
{
return ! is_null($this->__get($key));
}
/**
* Get an input element from the request.
*
* #param string $key
* #return mixed
*/
public function __get($key)
{
if (array_key_exists($key, $this->all())) {
return data_get($this->all(), $key);
}
return $this->route($key);
}
}
Thanks
I did this and it works perfectly.
1. composer.json:
From:
"require": {
"php": ">=7.0.0",
"fideloper/proxy": "~3.3",
"laravel/framework": "5.5.*",
"laravel/tinker": "~1.0"
},
To:
"require": {
"php": ">=7.1.3",
"fideloper/proxy": "~4.0",
"laravel/framework": "5.6.*",
"laravel/tinker": "~1.0"
},
2. Replace app\Http\Middleware\TrustedProxies.php file with contents below:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* #var array
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* #var string
*/
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
3. composer update
Laravel's Request object extends Symfony's Request object. Laravel 5.5 depends on Symfony 3, which has that constant. Laravel 5.6 depends on Symfony 4, which does not have that constant.
Based on your trusted proxies configuration, it looks like you're using the trusted proxies package "outside" of Laravel. Laravel brought the trusted proxies package inside the framework in 5.5, and created a dedicated \App\Http\Middleware\TrustProxies middleware for you to use.
I would suggest moving to use the middleware and configuring it as described in the Laravel documentation. This will help prevent this type of compatibility issue in the future.
To make the switch:
In app/Http/Kernel.php, if \Fideloper\Proxy\TrustProxies::class is in your $middleware array, remove it. If \App\Http\Middleware\TrustProxies::class is not in your $middleware array, add it.
Open your app/Http/Middleware/TrustProxies.php file and update it with your proxies.
Delete your config/trustedproxy.php file.
Remove Fideloper\Proxy\TrustedProxyServiceProvider::class from your providers array in config/app.php.
Update your composer.json file to use "fideloper/proxy": "~4.0". Run composer update fideloper/proxy to update the package.
I have updated from 5.5 to 5.6
composer.json
"minimum-stability":"dev",
"prefer-stable": true,
This will install latest Laravel packages, then there will be issue with TrustedProxies.
Install the latest proxy version for Laravel 5.6.
Please use tag 4.0+ for Laravel 5.6:
composer require fideloper/proxy:~4.0
More details
First install Laravel 5.6 i faced this error as well.
Just follow the few steps below will fix it:
Make sure your file composer.json requirement has:
"require": {
"php": "^7.1.3",
"fideloper/proxy": "^4.0",
},
Then try composer update to make sure your composer is up-to-date
Finally run: composer require fideloper/proxy:~4.0
Done!
To anyone who tried upgrading directly from laravel 5.5 to 5.7, and got this problem too, remove the trustedproxy.php file from app->config->trustedproxy.php.
Hopes that helps someone.
Just need to Change fideloper/proxy in composer.json file:-
Your composer.json file now:-
"fideloper/proxy": "~3.3",
Change it to ^4.0 somthing like this:-
"fideloper/proxy": "^4.0",
After that you need to run update composer that's it.
composer update
Your problem comes from your use of the library TrustedProxy.
It uses Symfony's HEADER_CLIENT_IP constant which was deprecated with Symfony 3.3 and completely removed in Symfony 4.0.
Since Laravel 5.6 has updated to use Symfony 4 components, this will no longer work.
The way to solve it is to do what patricus suggested and use Laravel's TrustProxies middleware.
I did the following things and got my project to run on Laravel 5.6-dev:
Followed what patricus
suggested
Changed fideloper/proxy to "~4.0", and added "minimum-stability":
"dev", "prefer-stable": true at the end of my composer.json file.
Replace app\Http\Middleware\TrustedProxies.php by:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
protected $proxies;
protected $headers = Request::HEADER_X_FORWARDED_ALL;
}
Replace config\trustedproxy.php by:
<?php
return [
'proxies' => null,
'headers' => Illuminate\Http\Request::HEADER_X_FORWARDED_ALL,
];
None of the suggestions here worked for me for some reason. I am using quickadmin panel and various dependencies which might have something to do with it.
What finally worked was removing laravel/dusk, then updating to "fideloper/proxy": "~4.0", on it's own. Then updating laravel/framework to 5.6, then reinstalling dusk.
I did not need:
"minimum-stability":"dev",
"prefer-stable": true,
Maybe that was fixed with recent updates.
Faced the same issue and got a number of guidelines to resolve this. Unfortunately none of those worked or me. Actually there is no additional step or tasks needed to be addressed to fix this issue.
Just follow the official upgrade guide from https://laravel.com/docs/5.6/upgrade and along with that remove the trustedproxy config file located at config/trustedproxy.php
Had the same issue in Laravel 5.7. You may add TELESCOPE_ENABLED=false in your .env or .env.dusk.local :Source

DataFixture aren't saved using nelmio/alice ( sf 3.3 with flex)

Hello I'm using flex to work with Symfony for learning purpose. After I installed a few recipes and I want to add the nelmio/alice for generating fake data for doctrine fixtures but after I load the fixtures no data is saved into mysql. Any ideas what did i do wrong?
<?php
namespace App\DataFixtures\ORM;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Nelmio\Alice\Loader\NativeLoader;
class LoadFixtures extends Fixture
{
/**
* Load data fixtures with the passed EntityManager
*
* #param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
$loader = new NativeLoader();
$obj = $loader->loadFile(__DIR__ . 'fixtures.yml');
}
fixtures.yml:
App\Entity\BaseUser:
user{1..10}:
email: <email()>
BaseUser entity
<?php
namespace App\Entity;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Class BaseUser
* #package App\Entity
* #ORM\Entity
* #ORM\Table()
*/
class BaseUser implements AdvancedUserInterface
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", unique=true)
*/
private $email;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
* #return BaseUser
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* #param mixed $email
* #return BaseUser
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* #return bool true if the user's account is non expired, false otherwise
*
* #see AccountExpiredException
*/
public function isAccountNonExpired()
{
// TODO: Implement isAccountNonExpired() method.
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* #return bool true if the user is not locked, false otherwise
*
* #see LockedException
*/
public function isAccountNonLocked()
{
// TODO: Implement isAccountNonLocked() method.
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* #return bool true if the user's credentials are non expired, false otherwise
*
* #see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
// TODO: Implement isCredentialsNonExpired() method.
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* #return bool true if the user is enabled, false otherwise
*
* #see DisabledException
*/
public function isEnabled()
{
// TODO: Implement isEnabled() method.
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* #return (Role|string)[] The user roles
*/
public function getRoles()
{
return ['ROLE_USER'];
}
/**
* Returns the password used to authenticate the user.
*
* This should be the encoded password. On authentication, a plain-text
* password will be salted, encoded, and then compared to this value.
*
* #return string The password
*/
public function getPassword()
{
// TODO: Implement getPassword() method.
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
// TODO: Implement getSalt() method.
}
/**
* Returns the username used to authenticate the user.
*
* #return string The username
*/
public function getUsername()
{
return $this->email;
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
bundles.php
<?php
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineCacheBundle\DoctrineCacheBundle::class => ['all' => true],
Doctrine\Bundle\DoctrineBundle\DoctrineBundle::class => ['all' => true],
Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle::class => ['all' => true],
Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle::class => ['all' => true],
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle::class => ['all' => true],
];
and in frameworky.yml i added this
nelmio_alice:
locale: 'en_US' # Default locale for the Faker Generator
seed: 6399 # Value used make sure Faker generates data consistently across
# runs, set to null to disable.
functions_blacklist: # Some Faker formatter may have the same name as PHP
- 'current' # native functions. PHP functions have the priority,
# so if you want to use a Faker formatter instead,
# blacklist this function here
loading_limit: 5 # Alice may do some recursion to resolve certain values.
# This parameter defines a limit which will stop the
# resolution once reached.
max_unique_values_retry: 150 # Maximum number of time Alice can try to
# generate a unique value before stopping and
# failing.
composer.yml
{
"type": "project",
"license": "proprietary",
"require": {
"php": "^7.0.8",
"doctrine/doctrine-fixtures-bundle": "^2.4",
"doctrine/doctrine-migrations-bundle": "^1.2",
"sensio/framework-extra-bundle": "^5.0",
"sensiolabs/security-checker": "^4.1",
"symfony/console": "^3.3",
"symfony/framework-bundle": "^3.3",
"symfony/orm-pack": "^1.0",
"symfony/security-core": "^3.3",
"symfony/yaml": "^3.3"
},
"require-dev": {
"nelmio/alice": "^3.1",
"symfony/dotenv": "^3.3",
"symfony/flex": "^1.0"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
},
"scripts": {
"auto-scripts": {
"cache:clear": "symfony-cmd",
"assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd",
"security-checker security:check": "script"
},
"post-install-cmd": [
"#auto-scripts"
],
"post-update-cmd": [
"#auto-scripts"
]
},
"conflict": {
"symfony/symfony": "*",
"symfony/twig-bundle": "<3.3",
"symfony/debug": "<3.3"
},
"extra": {
"symfony": {
"id": "01BX9RZX7RBK5CNHP741EVCXB5",
"allow-contrib": false
}
}
}
I was trying to follow the KNP Symfony video tutorial and got lost on Nelmio/Alice repo. Bogdan's answer worked for me.
You need to add Alice Data Fixtures repo.
After adding
Here's a quick guide for all of you who's also lost:
namespace AppBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DataFixtures extends Controller implements FixtureInterface
{
public function load(ObjectManager $manager)
{
//File Path/s needs to be in array
$dummyFilePath =[__DIR__.'/DataFixtures.yml'];
//get fidry loader
$loader = $this->get('fidry_alice_data_fixtures.doctrine.loader');
//execute
$loader->load($dummyFilePath);
}
}
I solved the problem by installing theofidry/alice-data-fixtures since it seems nelmio/alice 3.x doesn't work the same as the older version. ( It doesn't takes care of the database query anymore ) .
LE:
Maybe it's my fault or not but since the official release of the sf 4 i had some problems with the loading part.
Here's a fix for anyone looking into
You need a service like this to load the fixtures
App\DataFixtures\ORM\DataFixtures:
arguments: ['#fidry_alice_data_fixtures.doctrine.purger_loader']
calls:
- [load, ['#doctrine.orm.entity_manager']]
tags: [doctrine.fixture.orm]
And in the method
$files = [
__DIR__ . '/fixtures.yml',
];
$this->loader->load($files);

Why laravel 4.1 is giving class does not exist error for a namespaced class?

I'm having an issue in laravel 4.1. I'm following a tutorial series. I have "Acme/Transformers" folder in "app" directory which has two class "Transformer.php" and "LessonTransformer.php". When i tried to access "LessonTransformer.php" in LessonController class of Controller directory i'm getting the following issue.
ReflectionException
Class Acme\Transformers\LessonTransformer does not exist
I updated my composer.json file like following.
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/Acme"
],
"psr-0":{
"Acme" : "app/Acme"
}
and ran
"composer dump-autoload -o"
but it made no change in the output. I have no ideas what's going on. Please help me.
Here's is my LessonsController.php class
use Acme\Transformers\LessonTransformer;
class LessonsController extends \BaseController {
/**
* #var Acme\Transformers\LessonTransformer
*/
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer){
$this->lessonTransformer = $lessonTransformer;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
$lessons = Lesson::all();
return Response::json([
'lessons' => $this->lessonTransformer->transformCollection($lessons->toArray())
], 200);
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$lesson = Lesson::find($id);
if(!$lesson){
return Response::json([
'error' => [
'mesage' => 'Lessons does not exits'
]
], 404);
}
return Response::json([
'lesson' => $this->lessonTransformer->transform($lesson)
], 200);
}
/**
* Map over the lesson collection and cast it in an array,
* so that we can map over it.
*
* Transform a collection of lesson
*
* #param array $lessons
* #return array
*/
public function transformCollection(array $lessons){
return array_map([$this,'transform'], $lessons);
}
/**
* Transform a single object(lesson)
* Instead of returning everything, we return some selected data.
* We replaced the keys that exposed the DB structure with some
* other keys because if we wish to change the keys of data in
* future then we can change it without affecting the DB structure.
*
* #param array $lesson
* #return array
*/
public function transform($lesson){
return [
'title' => $lesson['title'],
'body' => $lesson['body'],
'active' => (boolean)$lesson['some_bool']
];
}
}
maybe you forget to update your composer.json: add app/Acme to classmap
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/Acme"
]
},
and run composer dump-autoloadon your terminal
Have you added the
namespace Acme\Transformers;
line at the top of the LessonTransformer.php file?
Also check for plurality of the filenames. Often mistakes come from a file named LessonTransformer.php and the class named LessonsFormatter (mind the s).
EDIT
These should be the top lines of your files:
app/src/Acme/Transformers/Transformer.php
<?php
namespace Acme\Transformers;
class Transformer
{
app/src/Acme/Transformers/LessonTransformer.php
<?php
namespace Acme\Transformers;
class LessonTransformer extends Transformer
{
app/controllers/LessonsController.php
<?php
use Acme\Transformers\LessonTransformer;
class LessonsController extends BaseController
{

Categories