I am using laravel 4.1 and working on my own package in workbench. I added extra repo (sentry 2) in my package composer.json. Sentry is working properly but I can't override config by loading config files from workbench/package/name/src/config/packages/cartalyst/sentry/config.php
My service Provider looks like that:
public function boot()
{
// https://coderwall.com/p/svocrg
$this->package('package/name');
$config_path = __DIR__ . "/../../config/packages/cartalyst/sentry";
$this->app['config']->package('cartalyst/sentry', $config_path, 'cartalyst/sentry');
$this->app->register('Cartalyst\Sentry\SentryServiceProvider');
include __DIR__.'/../../routes.php';
}
public function register()
{
$this->app->booting(function()
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Sentry', 'Cartalyst\Sentry\Facades\Laravel\Sentry');
});
}
When I override something in config.php (workbench/package/name/src/config/packages/cartalyst/sentry/config.php) I still get things from vendor/cartalyst/sentry/src/config/config.php. How to properly load config in workbench package
I think you can't because as explained at official cartalyst sentry website "sentry is third party"
but you still can do some trick in your composer file in workbench.
at your composer.json in workbench :
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize",
"php artisan app:sentry" /* add your own command which organize to create your own sentry configuration (remember mkdir cartalyst/sentry/config.php store to app/config/packages) */
],
// more
},
this mean, when your package in installing, your own command (e.g : php artisan app:sentry) will be executed
hope this help you...
Or, alternatively (more simple)
in your composer scripts key add :
"php artisan config:publish --package=cartalyst/sentry"
and then, at boot method in your PackageServiceProvider,
set your own configuration.
for example :
public function boot()
{
// for change user sentry model
\Config::set('sentry::config.user.model', 'Vendor\Package\YourUserModel');
}
I think this is more simplest way. :)
Example below show how i add config override of Basset in my package(workbench). You have to put this code in your register method in you service provider.
// Get config loader
$loader = $this->app['config']->getLoader();
// Add package namespace with path set base on your requirement
$loader->addNamespace('basset',__DIR__.'/../config/basset');
// Load package override config file
$configs = $loader->load($this->app['config']->getEnvironment(),'config','basset');
// Override value
$this->app['config']->set('basset::config',$configs);
Related
I've written a custom Artisan command (let's call it MyDusk.php) that expands/abstracts some of the functionality of the core Dusk command.
This custom command extends Laravel\Dusk\Console\DuskCommand from within the Dusk package.
The problem is, on production the Dusk package is not installed (it's under require-dev in composer.json)
So when composer is generating its autoload files on production, it errors out when it gets to MyDusk.php because it can't find Laravel\Dusk\Console\DuskCommand.
PHP Fatal error: Class 'Laravel\Dusk\Console\DuskCommand' not found in app/Console/Commands/Dusk.php on line 10
In Dusk.php line 10:
Class 'Laravel\Dusk\Console\DuskCommand' not found
I tried moving the Dusk package to require so it would be available on production (not ideal, I know), but there's a line in the core Dusk service provider that throws an exception when it's run on production preventing this:
# From: vendor/laravel/dusk/src/DuskServiceProvider.php
if ($this->app->environment('production')) {
throw new Exception('It is unsafe to run Dusk in production.');
}
I'm trying to think of the most elegant solution to allow for my custom Dusk command to be part of the application and accessible locally, without throwing errors on production.
One idea: Write my Dusk command as its own package, that's also only in require-dev.
Any other ideas?
I just took a look at the API, you could do this:
You could move your command to App\Console\Commmands\Local\DuskCommand.php.
By default, if you check the commands() method in the Kernel, it's only going to load commands found in App\Console\Commands. This will not include the sub-directories.
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
This is the default commands() method. You could switch this implementation to the one below:
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$paths = [
__DIR__ . '/Commands'
];
if(app()->environment('local')) {
$paths[] = __DIR__ . '/Commands/Local';
}
$this->load($paths);
require base_path('routes/console.php');
}
So, in local, we are also going to load commands based in App\Console\Commands\Local.
Admittedly, I didn't give this a try myself, but I am assuming that it should work.
Edit: I gave it a try and it seems to be working just fine. I thought, I'd try to explain it a bit more. Basically, after doing a composer dump-autoload, Laravel is listening to this event and doing two things:
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover --ansi"
]
The second one is trying to run the Auto-Package Discovery command and this is where it will fail. The Artisan executable actually boots the application with the Console Kernel.
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
While resolving the Kernel, it will also try to boot up the Commands that it needs so that they are available to Artisan, and this is where it fails.
However, like I mentioned above, if you only boot the Commands you need in production, this issue won't happen.
Accepted answer seems not to work in Laravel 6. This worked for me:
Create your command with php artisan make:command YourCommand and move it to app/Console/Local.
Change its namespace to App\Console\Local.
Then, in app/Console/Kernel.php:
protected function commands()
{
$paths = [
__DIR__ . '/Commands'
];
if(app()->environment('local')) {
$paths[] = __DIR__ . '/Local';
}
$this->load($paths);
require base_path('routes/console.php');
}
Enjoy ;)
I make right usage of Laravel's facades and PhpStorm gives me warnings, why is that?
And on image I pointed "x" for some...types of data? In functions I use, why do I have these? How to remove them?
Using facades with Laravel
Luke Waite is right:
You're not using facades. You've imported the classes, and on the
first, Categories, the IDE is telling you that the get method is not a
static method.
Just import the facade instead (if it exist).
See the documentation on Facades to learn more on how to use the available facades and how to define your own.
A facade class should look like this:
use Illuminate\Support\Facades\Facade;
class Cache extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'cache';
}
}
Where the 'cache' string is the name of a service container binding and defined in a service provider, something like this:
use App\Cache\MyCache;
use Illuminate\Support\ServiceProvider;
class CacheServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
$this->app->singleton('cache', function ($app) {
return new MyCache();
});
}
}
Fixing the warnings with Facades
That being said, I was tired of the warnings and the missing auto-completion and highlighting with facades so I also searched to find a way to fix these.
I came upon laravel-ide-helper which adds Laravel CLI commands that generates php files that only serves to be parsed by your IDE.
Install
Require this package with composer using the following command:
composer require barryvdh/laravel-ide-helper
After updating composer, add the service provider to the providers
array in config/app.php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, To
install this package on only development systems, add the --dev flag
to your composer command:
composer require --dev barryvdh/laravel-ide-helper
In Laravel, instead of adding the service provider in the
config/app.php file, you can add the following code to your
app/Providers/AppServiceProvider.php file, within the register()
method:
public function register()
{
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
// ...
}
This will allow your application to load the Laravel IDE Helper on
non-production enviroments.
Automatic phpDoc generation for Laravel Facades
You can now re-generate the docs yourself (for future updates)
php artisan ide-helper:generate
Note: bootstrap/compiled.php has to be cleared first, so run php artisan clear-compiled before generating (and php artisan
optimize after).
You can configure your composer.json to do this after each commit:
"scripts":{
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan ide-helper:generate",
"php artisan ide-helper:meta",
"php artisan optimize"
]
},
The .phpstorm.meta.php and _ide_helper.php files will be generated and should be added to your .gitignore as you don't want to commit these.
I am developing a blog as a custom package for Laravel 5.3.
So far I have got the routes, controller, models and migrations working.
I am now working on the CRUD. For the forms I thought I could use this:
https://laravelcollective.com/docs/5.3/html
UPDATE
I have installed the package with composer. The dependency is in the composer.json file. The files are in my package's vendor folder.
I have also tried to run composer dump-autoload -o
From my composer.json
"require": {
"laravelcollective/html": "5.3.*"
}
I have looked everywhere and people suggest to do the following:
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
// Bind the app.
$this->app->bind('blog', function ($app) {
return new Blog;
});
// Register LaravelCollective Form Builder.
$this->app->register('Collective\Html\HtmlServiceProvider');
$this->app->alias('Form', 'Collective\Html\FormFacade');
$this->app->alias('Html', 'Collective\Html\HtmlFacade');
}
I currently get the following error everywhere:
FatalThrowableError in Application.php line 610:
Class 'Collective\Html\HtmlServiceProvider' not found
Really not sure where I am going wrong.
UPDATE
I have tried bind instead of register:
$this->app->bind('Collective\Html\HtmlServiceProvider');
But this time I get the following error:
Class 'Collective\Html\FormFacade' not found
Make sure your composer.json contains the dependency laravelcollective/html, if not, add it to your composer.json or include it via the following command composer require laravelcollective/html
Make sure you've added the dependency to providers and aliases in config/app.php
'providers'=>[
Collective\Html\HtmlServiceProvider::class,
],
'aliases'=>[
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
],
I use Lumen 1.0 for an API project.
I have already enable Eloquent by uncomment the following line in bootstrap/app.php file :
$app->withEloquent();
But when I want to create my first model with migration it fails :
php artisan make:model Book --migration
Error message :
[InvalidArgumentException]
Command "make:model" is not defined.
Did you mean one of these?
make:seeder
make:migration
Laravel doc about Eloquent (http://laravel.com/docs/5.1/eloquent#defining-models).
Lumen doc (http://lumen.laravel.com/docs/installation) doesn't include Eloquent doc because, it's not enable by default.
Do you have any ideas to avoid this error ?
Add details
php artisan --version
Displays :
Laravel Framework version Lumen (5.1.6) (Laravel Components 5.1.*)
You're seeing this error because Lumen doesn't come with make:model.
To see a list of all the artisan commands you have at your disposal just run php artisan.
That being said I did just find this package which I've added to a lumen installation and it seems to work fine https://github.com/webNeat/lumen-generators#installation
Hope this helps!
If you check all the available commands using php artisan list you will see that you don't have all the default ones offered by laravel. But you can get the most importants using the lumen-generator package (not to be confused with lumen-generators). It has the advantage of offering more commands than the other one mentioned.
To use it just install it using composer:
composer require flipbox/lumen-generator
Then enable it in your bootstrap/app.php file:
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
You will now be able to use all these new commands using artisan:
key:generate Set the application key
make:command Create a new Artisan command
make:controller Create a new controller class
make:event Create a new event class
make:job Create a new job class
make:listener Create a new event listener class
make:mail Create a new email class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:policy Create a new policy class
make:provider Create a new service provider class
make:seeder Create a new seeder class
make:test Create a new test class
Just have a look at the official documentation: https://github.com/flipboxstudio/lumen-generator
Go to the project directory and add the generators package to your composer.json using the following command:
composer require wn/lumen-generators
Add following code segment to app/Providers/AppServiceProvider.php:
public function register()
{
if ($this->app->environment() == 'local') {
$this->app->register('Wn\Generators\CommandsServiceProvider');
}
}
Make sure that you have un-commented the following line in bootstrap/app.php to allow service providers on your project:
$app->register(App\Providers\AppServiceProvider::class);
Run php artisan list on the project directory (document root). Now you will see new items there.
just create your model file manually in the app directory
example
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $table = ‘articles’;
protected $fillable = [
‘title’,
‘description’,
‘body’
];
}
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class); add this line into "bootstrap\app.php" and save this file then make the command.It will work.
there are some packages that can help you to have all of artisan command that you has on Laravel .
install below package to have more artisan command.
https://github.com/flipboxstudio/lumen-generator
So my migrations folder looks like this since I have dozens of tables it keeps things organized and clean:
migrations/
create_user_table.php
relations/
translations/
I'm trying to do a refresh all migrations and seed but it seems like I've run into a slight hiccup where I don't know the artisan command to run migrations recursively (i.e. run migrations in the relations and translations folders as well).
I've tried adding --path="app/database/migrations/*" however it spat out an error. Does anyone know the solution to this?
The only way to do it right now is to manually go through all the migrations. That is, you have to run the migration command on each of your subfolders:
php artisan migrate --path=/app/database/migrations/relations
php artisan migrate --path=/app/database/migrations/translations
However, what you can do is easily extend the artisan system to write your own migrate command that will iterate through all folders under the migrations folder, create these commands for you and run them.
You can also simply write a shell script if you don't want to get into doing this via artisan
Edit: for Laravel >= 5.0, the correct commands to migrate migration files in sub directories would be:
php artisan migrate --path=/database/migrations/relations
php artisan migrate --path=/database/migrations/translations
This add to boot method in AppServiceProvider
$mainPath = database_path('migrations');
$directories = glob($mainPath . '/*' , GLOB_ONLYDIR);
$paths = array_merge([$mainPath], $directories);
$this->loadMigrationsFrom($paths);
Now you use can php artisan migrate and also php artisan migrate:back
You can also use a wildcard, like so:
php artisan migrate --path=/database/migrations/*
You can use the following command to do this recursively:
php artisan migrate --path=/database/migrations/**/*
**/* is also known as the globstar
Before this works you must check if your bash supports the globstar.
You can do this by executing shopt and checking for globstar.
Globstar is supported by default by most server distributions but might not work on MAC.
For more on globstar see: https://www.linuxjournal.com/content/globstar-new-bash-globbing-option
In Laravel 5 the database folder sits alongside the app folder by default. So you could run this to migrate a single folders migrations:
php artisan migrate --path=/database/migrations/users
You can try this package nscreed/laravel-migration-paths. By default all sub directories inside the migrations folder will be autoloaded. Even you can add any directories very easily.
'paths' => [
database_path('migrations'),
'path/to/custom_migrations', // Your Custom Migration Directory
],
Don't need any special command just the generic: php artisan migrate will do your tasks.
I rewrote the MigrationServiceProvider:
- registerResetCommand()
- registerStatusCommand()
- registerMigrateCommand()
There you can register your own commands:
class MigrateCommand extends Illuminate\Database\Console\Migrations\MigrateCommand
After that you just need to extend youd directories:
protected function getMigrationPaths()
Or you just register the paths on application boot.
I've already done my solution before I knwewd about '$this->loadMigrationsFrom'.
A Simple solution is to create an Artisan Command for example (migrate:all),
then inside handle function define migrate command for each sub directories as mentioned bellow.
Artisan::call('migrate', [
'--path' => '/database/migrations/employee'
]);
Only relative path works for me (in Laravel 5.7):
php artisan migrate --path=database/migrations/your-folder-with-migrations
This works at laravel 8
php artisan migrate --path=database/migrations/tenant
It is a not a "direct" solution but i suggest you to look at Modularity into your laravel project.
Modules can segment your application in several smaller "folders" and bring migration, seeds, classes, routes, controllers, commands together in easily maintainable folders.
This package is a good start : https://github.com/pingpong-labs/modules
No changes are necessary, whenever you need it, use this command:
php artisan migrate --path=database/migrations/*
If you want a shortcut, you can include that in your composer.json:
"scripts": {
"migrate": [
"#php artisan migrate --force --path=database/migrations/*"
]
}
Then just use composer migrate in the terminal.
add in app/Providers/AppServiceProvider.php the path of your migration folder, you can add a string or an array
public function register()
{
$this->registerMigrations();
}
protected function registerMigrations()
{
return $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations/**/*');
}
A Simple Laravel solution is to create a gulp task (say migrate-others).
var elixir = require('laravel-elixir');
var gulp = require('gulp');
var shell = require('gulp-shell')
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
// Our Task
gulp.task('migrate-others', shell.task([
'php artisan migrate --path=/app/database/migrations/relations',
'php artisan migrate --path=/app/database/migrations/translations',
]));
Now you can simply call
gulp migrate-others
Here you go!
function rei($folder)
{
$iterator = new DirectoryIterator($folder);
system("php artisan migrate --path=" . $folder);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
rei($folder . $fileinfo->getFilename() . '/');
}
}
}
rei('./database/');