run artisan command from php function - php

I want to run php artisan passport:client --password from function.
I tryed Artisan::call('passport:client'); and Artisan::command('passport:client'); but it return undefined command
Note: I have alredy install laravel passport and the command is working fine from the terminal

I have found it, in boot() method of the PassportServiceProvider there is a check that essentially prevent it being called from Artisan::call.
//PassportServiceProvider.php at line 37:
if ($this->app->runningInConsole()) {
$this->commands([
Console\InstallCommand::class,
Console\ClientCommand::class,
Console\KeysCommand::class,
]);
...
}
to make it work with general artisan command, we can register these commands ourselves. somewhere within the boot method of AuthServiceProvider maybe.
public function boot() {
$this->commands([
Console\InstallCommand::class,
Console\ClientCommand::class,
Console\KeysCommand::class,
]);
}
Now we can call Artisan::call('passport:install') or the other 2 commands.

From Laravel Docs
Route::get('/foo', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);
//
});

Import this line on top.
use Illuminate\Support\Facades\Artisan;
And Enter line below for command
Artisan::call('passport:client --password')

Related

Laravel 9/Passport not working in production

I just deployed a Laravel 9 Passport based API to Digital Ocean. Everything works fine, but when I try lo log an user or an admin and create a token to be stored and returned, I get 500 server error.
I already ran php artisan passport:keys. Because it wasn´t working, I tried to pass the keys by .env through php artisan vendor:publish --tag=passport-config, but still got the error.
Here is my LoginController:
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (!Auth::attempt($credentials)) {
return response()->json([
'message' => 'Usuario y/o contraseña inválidas'
], 401);
}
// If I comment this line and the accessToken in the json response, and return just the Auth::user(), it works fine
$accessToken = Auth::user()->createToken('my_token')->accessToken;
return response()->json([
'user' => Auth::user(),
'accessToken' => $accessToken
], 200);
}
This is my AuthServiceProvider.php boot method:
public function boot()
{
$this->registerPolicies();
/* Passport::routes(); */
if (!$this->app->routesAreCached()) {
Passport::routes();
}
/**
* Controls the expire time for the access token
*/
Passport::personalAccessTokensExpireIn(now()->addDays(30));
Passport::tokensCan([
'admin' => 'Admin',
'user' => 'User',
]);
}
No errors related are being logged neither in Laravel logs nor in nginx ones.
Thanks for your help.
So I figured out the solution with aynber guess.
I try catched the accesstoken line and set debug to true.
It was missing the Personal Client ID, so I ran php artisan passport:client --personal and it worked.
That happens because the client id is self-generated when you first run artisan passport:install.
But when you are cloning a repo and running a migration and a composer install command, you really never run passport:install, so a new client personal id must be run manually.

Twitter API asatymic/twitter with Laravel 8

I followed his readme and I have done composer dump-autoload a million times, but still I receive an error. Don't know what i am making wrong. I am trying to use v2 version of twitter api. Please help me anyone.
In config/app.php:
'providers' => [
...
Atymic\Twitter\ServiceProvider\LaravelServiceProvider::class,
],
'aliases' => [
...
'Twitter' => Atymic\Twitter\Facade\Twitter::class,
],
In my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Twitter;
class HomeController extends Controller {
public function index() {
$tweets = Twitter::getUserTimeline([
'screen_name' => 'xxxxxxx',
'count' => 10,
'format' => 'json'
]);
dd($tweets);
return view('home');
}
public function about() {
return view('about');
}
}
But I am getting this error:
Error
Call to undefined method Atymic\Twitter\Service\Accessor::getUserTimeline()
Look like you have to import facade
Instead of this
use Twitter;
Import this
use Atymic\Twitter\Facade\Twitter;
If you are using alias then run following command
php artisan config:clear
composer dump-autoload
php artisan optimize
Please look to the twitter api version which you have defined in the .env. you may need to use 1.1 and you are using v2
I think getUserTimeLine is available for version 1.1, and I think as the readme says you can use userTweets for v2

Insert image in database using faker library

Factory Class
$factory->define(Product::class, function (Faker $faker) {
return [
'image' => url("/images/{$faker->image('public/storage/images',640,480, null, false)}")
];
});
And after this command
php artisan db:seed
image column of database filled with this string
http://localhost/images/a1af4cb757aef7f6b181dfb978228767.jpg"
and when i seach this url on browser, i get "Unable to connect" error
You need to add storage in your link before images/image_name to be like this
http://localhost/storage/images/a1af4cb757aef7f6b181dfb978228767.jpg
Make sure that you run php artisan storage:link

How to force laravel to wait until the end job?

my function in controller Calling parallel and i create a job for use queue in laravel Because parallel call causing the problem
I create queue as follows :
public function serve($id)
{
$this->dispatch(new OrderServeJob($id));
return response()->json(true);
}
and i run:
php artisan queue:work
But I have a problem with this method
I want laravel to wait until the queue ends up and then return response()->json(true)
and after redirect user to another address
If you want your job to be handled before the call ends you should use the syncdriver for your Job. You can do this customizing the Job connection to use in your job:
class OrderServeJob implements ShouldQueue {
public $connection = 'sync'; // <---
//
}
You can take a look a this (and others) queue configuration in your config/queue.php file:
'connections' => [
'sync' => [
'driver' => 'sync',
],
//
]
Check the Customizing The Queue & Connection section of the documentation.
You can use queue events. Explanation how to use in the documentation:
job Events laravel
U can add ->onConnection('sync') to ur job firing
$this->dispatch(new OrderServeJob($id))->onConnection('sync');

Laravel passport install on dynamic database

I am creating database for each client registration in my laravel application. I have installed passport for authorization. I have successfully created database and ran migration for passport also. The passport:install command is not working for newly created database. Is there any way to run command passport:install for my new database.
$this->info(sprintf("Dropping database if exists : %s", $dbName));
DBHelper::drop($dbName);
$this->info("Setting up database for client");
//Create migration table
Artisan::call("migrate:install", array(
"--database" => DBHelper::connect($dbName)
));
//Run migration
Artisan::call('migrate',
array('--path' => 'database/migrations/client',
'--database' => DBHelper::connect($dbName))); //DBHelper::connect($dbName) : Create new database config and then DB::reconnect()
//Install passport migration
Artisan::call('migrate', ['--path' => 'vendor/laravel/passport/database/migrations']);
//Install passport
Artisan::call('passport:install');
//Populate database
Artisan::call('db:seed',
array('--database' => DBHelper::connect($dbName)));
After creating database use bellow commands for creating migrations and install passport.
Artisan::call('migrate:refresh', ['--seed' => true]);
Artisan::call('migrate',['--path' => 'vendor/laravel/passport/database/migrations','--force' => true]);
shell_exec('php ../artisan passport:install');
Usually you would use the following code in your controller to excute an Artisan call:
Artisan::call('passport:install');
However, this doesn't work on passport:install and you will get the error:
There are no commands defined in the "passport" namespace
To fix this you must add the following code to boot method at AppServiceProvider.php :
<?php
namespace App\Providers;
use Laravel\Passport\Console\ClientCommand;
use Laravel\Passport\Console\InstallCommand;
use Laravel\Passport\Console\KeysCommand;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Schema::defaultStringLength(191);
Passport::routes();
/*ADD THIS LINES*/
$this->commands([
InstallCommand::class,
ClientCommand::class,
KeysCommand::class,
]);
}

Categories