Laravel/Passport - After remigration keys are not usable - php

Settings
Passport Version: "laravel/passport": "^9.3",
Laravel Version: "laravel/framework": "^7.0",
PHP Version: "php": "^7.2.5",
Database Driver & Version: MYSQL 8.0.15
Description:
I have used this article to create fresh API with laravel-passport. After installation I have successfully registered some users. Then after some coding I have needed to add some columns to existing tables. So after adding these columns I have used fresh command to remigrate all database.
php artisan migrate:fresh --seed
The operation was successfully and all tables(oauth tables also) have been created. But after this migration process existing passport grant tokens are not usable. When I register new User by sending normal AJAX request from web app interface I get this error.
Undefined property: stdClass::$refresh_token
I have tried many ways and researched about this issue but only after renewing old client and password keys process worked.
php artisan passport:install --force
Steps To Reproduce:
After installation passport just install and creating keys and migrate database. So everything will work. Then after remigrate database with command php artisan migrate:fresh . Then old keys will not be usable.

Even though this question is quite old. But we can use Event Listeners to achieve repeated steps.
Under app\Providers\EventServiceProvider.php add the following code in boot() method.
Laravel 9
public function boot()
{
parent::boot();
Event::listen(CommandFinished::class, function(CommandFinished $event) {
if($event->command === 'migrate:fresh') {
Artisan::call('passport:install', [ '--force' => true]);
echo Artisan::output();
}
});
}
I found the Illuminate\Database\Events\MigrationsEnded not working for my case. But other one, Illuminate\Console\Events\CommandFinished trigger on all command executions.

Do this to overwrite the existing keys and it will work
php artisan passport:install --force
Or you may publish Passport's configuration file using
php artisan vendor:publish --tag=passport-config
which will then provide the option to load the encryption keys from your environment variables:
Refer this for detailed instruction https://laravel.com/docs/7.x/passport

Related

Laravel Passport migrations not using default connection

I am updating an application for my organization from Laravel 5.4 to 8.8. One of the packages we're using is an OAuth2 implementation that is replaced with laravel/passport - so I'm trying to get that package working.
Following the directions here: https://laravel.com/docs/8.x/passport#installation, I've installed laravel/passport, and want to apply the migrations. Running php artisan migrate gives me an error saying "Database connection [mysql] not configured".
That's odd, because the default configured database connection is "uoda".
I have tried:
In config/database.php, duplicating the connection details for uoda to mysql.
Renaming uoda to mysql and changing the default connection to "mysql"
Creating a new config/passport.php file that looks like:
return [
'storage' => [
'database' => [
'connection' => 'uoda'
]
]
];
but this file isn't even being called.
Going into vendor/laravel/passport/config/passport.php and changing "storage.database.connection" to env('DB_CONNECTION', 'uoda'). I changed this back to mysql after renaming the 'uoda' connection as mentioned above.
After each of these I call php artisan cache:clear.
Nothing I do seems to cause the migration to use the actually configured connection properties. What am I missing?
Please ELI5 your responses - this is my first foray into Laravel so I know next to nothing about its intricacies.
Thanks.
I was missing an evidently important command:
php artisan config:clear

Backup database in Laravel 8

Am using https://spatie.be/docs/laravel-backup/v7/introduction for backup and I tried to backup database using php artisan backup:run but i got these errors:
Backup failed because The dump process failed with exitcode 2 : Misuse of shell builtins : sh: 1: /opt/lampp/bin/mysql/mysqldump: not found
Sending notification failed
Backup failed because: The dump process failed with exitcode 2 : Misuse of shell builtins : sh: 1: /opt/lampp/bin/mysql/mysqldump: not found
.
Swift_RfcComplianceException
Address in mailbox given [] does not comply with RFC 2822, 3.6.2.
at vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php:355
351▕ */
352▕ private function assertValidAddress($address)
353▕ {
354▕ if (!$this->emailValidator->isValid($address, new RFCValidation())) {
➜ 355▕ throw new Swift_RfcComplianceException('Address in mailbox given ['.$address.'] does not comply with RFC 2822, 3.6.2.');
356▕ }
357▕ }
358▕ }
359▕
+38 vendor frames
39 artisan:37
Illuminate\Foundation\Console\Kernel::handle()
What should I do ?
I think the problem is in database.php in this code
'dump' => [
'dump_binary_path' => '/opt/lampp/bin/mysql', // only the path, so without `mysqldump` or `pg_dump`
'use_single_transaction',
'timeout' => 60 * 5, // 5 minute timeout
],
Where can I find mysqldump on lampp Ubuntu ?
PS: I am using laravel 8 on Ubuntu
Laravel doesn't have official command to take db backup which you mentioned
You must use following package
https://spatie.be/docs/laravel-backup/v7/installation-and-setup
To know laravel default php artisan commands .You can run following command to defualt commands available in php artisan.
php artisan
The result will show like below
Laravel Framework 8.42.1
Usage:
command [options] [arguments]
Options:
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
--ansi Force ANSI output
--no-ansi Disable ANSI output
-n, --no-interaction Do not ask any interactive question
--env[=ENV] The environment the command should run under
-v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
Available commands:
clear-compiled Remove the compiled class file
db Start a new database CLI session
down Put the application into maintenance / demo mode
env Display the current framework environment
help Display help for a command
inspire Display an inspiring quote
list List commands
migrate Run the database migrations
optimize Cache the framework bootstrap files
serve Serve the application on the PHP development server
test Run the application tests
tinker Interact with your application
ui Swap the front-end scaffolding for the application
up Bring the application out of maintenance mode
auth
auth:clear-resets Flush expired password reset tokens
cache
cache:clear Flush the application cache
cache:forget Remove an item from the cache
cache:table Create a migration for the cache database table
config
config:cache Create a cache file for faster configuration loading
config:clear Remove the configuration cache file
db
db:seed Seed the database with records
db:wipe Drop all tables, views, and types
event
event:cache Discover and cache the application's events and listeners
event:clear Clear all cached events and listeners
event:generate Generate the missing events and listeners based on registration
event:list List the application's events and listeners
key
key:generate Set the application key
make
make:cast Create a new custom Eloquent cast class
make:channel Create a new channel class
make:command Create a new Artisan command
make:component Create a new view component class
make:controller Create a new controller class
make:event Create a new event class
make:exception Create a new custom exception class
make:factory Create a new model factory
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:notification Create a new notification class
make:observer Create a new observer class
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class
make:resource Create a new resource
make:rule Create a new validation rule
make:seeder Create a new seeder class
make:test Create a new test class
migrate
migrate:fresh Drop all tables and re-run all migrations
migrate:install Create the migration repository
migrate:refresh Reset and re-run all migrations
migrate:reset Rollback all database migrations
migrate:rollback Rollback the last database migration
migrate:status Show the status of each migration
notifications
notifications:table Create a migration for the notifications table
optimize
optimize:clear Remove the cached bootstrap files
package
package:discover Rebuild the cached package manifest
queue
queue:batches-table Create a migration for the batches database table
queue:clear Delete all of the jobs from the specified queue
queue:failed List all of the failed queue jobs
queue:failed-table Create a migration for the failed queue jobs database table
queue:flush Flush all of the failed queue jobs
queue:forget Delete a failed queue job
queue:listen Listen to a given queue
queue:prune-batches Prune stale entries from the batches database
queue:restart Restart queue worker daemons after their current job
queue:retry Retry a failed queue job
queue:retry-batch Retry the failed jobs for a batch
queue:table Create a migration for the queue jobs database table
queue:work Start processing jobs on the queue as a daemon
route
route:cache Create a route cache file for faster route registration
route:clear Remove the route cache file
route:list List all registered routes
sail
sail:install Install Laravel Sail's default Docker Compose file
sail:publish Publish the Laravel Sail Docker files
schedule
schedule:list List the scheduled commands
schedule:run Run the scheduled commands
schedule:test Run a scheduled command
schedule:work Start the schedule worker
schema
schema:dump Dump the given database schema
session
session:table Create a migration for the session database table
storage
storage:link Create the symbolic links configured for the application
stub
stub:publish Publish all stubs that are available for customization
ui
ui:auth Scaffold basic login and registration views and routes
ui:controllers Scaffold the authentication controllers
vendor
vendor:publish Publish any publishable assets from vendor packages
view
view:cache Compile all of the application's Blade templates
view:clear Clear all compiled view files
Updated:
Look like the issue is with dump_binary_path
so it should be 'dump_binary_path'=>'/opt/lampp/bin' in config file

Why Larecipe can't load correctly?

I installed Larecipe in the project and he can't load correctly. When i see "/docs/1.0/overview", get errors in console and layout can't be load.
Uncaught ReferenceError: CreateLarecipe is not defined
Uncaught ReferenceError: LaRecipe is not defined
I made package updates and unfortunately it did not help.
Laravel Framework 5.7.28
"binarytorch/larecipe": "^2.1",
This may be an issue with the LaRecipe service provider not being registered (or auto-registered).
Add the service provider to the providers array in config/app.php:
'providers' => [
// Other Service Providers
BinaryTorch\LaRecipe\LaRecipeServiceProvider::class,
],
I experienced the same thing.
Try running both these Artisan commands:
php artisan larecipe:install
php artisan vendor:publish --tag=larecipe_assets --force
Please try this. I think you have to recreate boostrap/cache/compiled.php file.
php artisan optimize

Laravel create customs packages with commands

I am looking to make a generic appointment system in Laravel and I want to use that in my other projects.
Is there any way to achieve by creating custom commands? For example, php artisan make:auth creates a complete login, register, forgot and reset password functionality.
I want to do the same, like php artisan appoitment : make and it should create the models, controllers and database migrations in that Laravel installation
php artisan make:command {command name}. You can see {command name} file in app/console/commands directory.
change $signature to appoitment:make.
add your command class to app/console/Kernel.php commands list.
for example:
php artisan make:command AppoitmentCommand
In Kernel.php : $commands = [
AppoitmentCommand::class
];
php artisan //you can see all commands

Laravel running migrations on "app/database/migrations" folder recursively

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/');

Categories