Laravel call method on any artisan command - laravel

Is it possible to set a method that changes a value in my database automatically when I run a php artisan command? What I'm trying to accomplish is change the value of the first row in my "domains" table to suit the url from my .env file automatically whenever I push codes to my live/staging environment. Are there any ways to do this automatically without me manually going into my DB and changing it.

You could setup a Listener for the native event CommandFinished and check if the command is the config:cache.
Event::listen('Illuminate\Console\Events\CommandFinished', function ($event) {
if ($event->command == 'config:cache') {
// Change domains table data using Eloquent or Query Builder
}
});
To learn more about Events, see: https://laravel.com/docs/5.7/events#generating-events-and-listeners

Related

Setting configuration values at runtime

I'm using laravel 5.8 and created a command that runs in the background to keep data updated.
web.php
Route::get('/admin/do_stuff', function () {
Artisan::call('do:stuff');
return 'Started!';
});
DoStuff.php
while(config('key.value')){
doStuff();
sleep(120);
}
Also got my route (mysite.com/admin/do_stuff) that will start this process, but now I want to add a new route (mysite.com/admin/stop_doing_stuff) to be able to stop it. I've seen in the documentation config variables could be set during runtime https://laravel.com/docs/5.8/configuration#accessing-configuration-values but this doesn't seem to be changing the value at all. Is this possible?
Reading the value from the .env file seems to work but that means I need to edit that file manually and that's not an option, also I could store the value in the database but would like to not doing it. Tried clearing the config cache but getting the same result

Best way share data across all view in Laravel

I have some data that I want to share across all views. I am using AppServiceProvider's boot method to share data.it is working fine with MySQL however with pgsql when I run composer or PHP artisan commands I am getting the following error,(i do fresh and seed database very often)
SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "news" does not exist
it took me a while to understand where is the real issue. I m still unable to understand if it is pgsql related error or something else, bellow is code in AppServiceProvider. if I comment this code everything works fine except where I m using this.
public function boot()
{
$activeClubs = (new TournamentService())->getAllActiveClubs();
$activeNews = (new TournamentService())->getActiveNews();
$activeTournaments = (new TournamentService())->getActiveTournament();
View::share(['activeClubs' => $activeClubs, 'activeTournaments' => $activeTournaments, 'activeNews' => $activeNews]);
}
can you please help me that how can i share data across all views that i don't get this error in future.
you can determine if the app is running from console or not and prevent loading data in console
if ( !app()->runningInConsole() ){
// it's not console.
}
you mentioned you want to load this data in all views but sometimes, its one view that loaded in all of your views e.g. the layout.app view.
if its the case I recommend using view composers instead of View::share() as it will pass the data to that view before render and it will only run if that view is included in the page (so basically it will solve your problem even without app()->runningInConsole() condition required )
view composers doc
simple example:
View::composer('view-name', function ($view) {
$view->with('key', 'value');
});

Dynamically Register Commands in Laravel

I am able to register Events programmatically Illuminate\Support\Facades\Event and it's listener method. I would like to register command dynamically a similar way. Is there a way to do it in Laravel? Or what is the best way of doing in Laravel except for registering it inside app/Console/Kernel.php ?
Update
I am able to register a single class via the following code.
use Illuminate\Console\Application as Artisan;
if (app()->runningInConsole()) {
Artisan::starting(function ($artisan) use ($commandClass) {
$artisan->resolveCommands($commandClass);
});
}
If you look into your app/Console/Kernel.php you should see a statement like this:
$this->load(__DIR__.'/Commands');
This means that all command classes saved in app/Console/Commands/ will be automatically loaded and registered. Furthermore, if you create a command using artisan, Ex: php artisan make:command MyCommand, the class will be stored in app/Console/Commands/MyCommand.php.
While method provided by Pablo could be a better option for a single directory but if you have commands spread across different namespaces and directories one may end up adding multiple entries in app/Console/Kernel.php
In my use case the $commandClass is pulled from multiple xml files spread across multiple composer packages, therefore, I had to use this approach:
use Illuminate\Console\Application as Artisan;
// fetch command classes from different sources and register it here.
if (app()->runningInConsole()) {
Artisan::starting(function ($artisan) use ($commandClass) {
$artisan->resolveCommands($commandClass);
});
}

Laravel Routes creating clashes with artisan migrate

Scenario
I have setup Laravel application routes in such a way that, where
Route::group(["domain" => getSubDomain()->sub_domain,"middleware"=>
["guest"]], function () {
//member routes
});
have one helper function getSubDomain()->sub_domain, which is checking sub_domain allowed in companies table. here is the helper function code
$domain = \App\Model\Company::where('sub_domain', request()->getHost())->whereIn("company_type_id", (array)$company_type_id)->first();
return !empty($domain) ? $domain : new \App\Model\Company(
[
"sub_domain" => !in_array(4, $company_type_id) ? env("sub_domain") : "",
"welcome_message" => env("welcome_message"),
"domain_flag" => "assets/images/dev-logo.png"
]);
In short this helper function will check in database about the sub domain is what? and based on valid sub domains routes are created.
Issue
This implementation is having requirement of sub_domain column from table and which is yet run using migration,
So when I am running migration using php artisan migrate it's showing me invalid column sub_domain.
This is creating conflict, that To run the migration routes are creating problem, and to prepare proper routes migration needs to be run.
Earlier the same implementation was using .env variables but that was bit tedious as the support of new domains is required.
Can anybody have solution to run migration without interfering Routes ?

laravel scout when does shouldBeSearchable get triggered

Lets say I have a shouldBeSearchable() set like this:
public function shouldBeSearchable()
{
return $this->is_active === 1;
}
By default in my app a newly created post gets is_active set to 1 so it will be added to my search index.
But if I now update that same post and set is_active to 0 does it automatically then get removed from my search index?
Yes, it should. 👍
If it doesn't work, it will be a bug.
Run php artisan scout:flush "App\Models\YourModel".
Then run php artisan scout:import "App\Models\YourModel.

Resources