Calling One Laravel API Routes On Another Laravel Project - json

I've two LARAVEL projects one contains API routes and second contains the views
API end point is running on port 8000 using command php artisan serve
second one is running on port 8001 using command php artisan serve --port 8001
I want to display the JSON from API end point to the view
what are the possible ways to do this
I want to perform test my JSON data for view that's why doing this
Currently doing this
$response = $client->request('GET',
'http://localhost:8000/api/generate/token', [
'headers' => [
'Accept' => 'application/json',
],
]
);
return json_encode($response);
but this returns error Client error 404 Not Found

I was facing the same issue and this is how I solved it.
1, Run this command
composer require guzzlehttp/guzzle:~6.0
2, Implement your logic like this.
$client = new \GuzzleHttp\Client();
$response = $client->request('POST',
'your endpoint', [
'headers' => [
'Accept' => 'application/json',
],
]
);
return json_encode($response);
For more details check this website
https://docs.guzzlephp.org/en/stable/quickstart.html#making-a-request

Maybe you should run php artisan cache:clear and then run php artisan serve --port=<your_prefered_port>

Related

Yii2 - Extend a controller into an exist module

I want to extend a controller from the backend / controller into a my existed module.
The structure of directory in My Yii2 Application as follows.
``
backend
controllers
JobOrderController
view
job-order
modules
marketing
controllers
JobOrderController [extend from #backend \ controllers \ JobOrderController]
``
When I access the route: localhost / marketing / job-order, I get an error message:
``
View not Found - yii \ base \ ViewNotFoundException
The view file does not exist:
../../advanced/backend/modules/marketing/views/job-order/index.php
``
I don't want to change any view from the marketing module, is it possible?
Just use controllerMap in Module config.
Also set the view folder.
public function init()
{
parent::init();
// custom initialization code goes here
$this->controllerMap = [
'job-order' => [
'class' => 'backend\components\controllers\JobOrderController',
'viewPath' => Yii::getAlias('#backend') . '/components/views/job-order'
]
];
}

yii2-advanced:how can i save image in backend and view that in backend and frontend?

hi i am save image in frontend and that show in frontend true and i test with many way to view that in backend but don't work.
please help me
my controller in backend
Yii::$app->params['uploadPath'] = Yii::getAlias('#frontend') .'/web/uploads/';
$path = Yii::$app->params['uploadPath'] . $model->image_web_filename;
$image->saveAs($path);
url my backend and frontend is seperate
backend:yii.com/:81
frontend:yii.com
i test these soloution but didn't work true:
https://stackoverflow.com/questions/23155428/how-to-get-root-directory-in-yii2
i inset two alias in aliases file in backend\config:
Yii::setAlias('#frontend', 'http://frontend.sample.dev');
Yii::setAlias('#backend', 'http://backend.sample.dev');
and use that in backend/web/index.php
require(__DIR__ . '/../config/aliases.php');
but i get this error:
An Error occurred while handling another error:
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "site/error".' in
/var/www/blog/vendor/yiisoft/yii2/base/Module.php:532
Stack trace:
#0 /var/www/blog/vendor/yiisoft/yii2/web/ErrorHandler.php(95):
yii\base\Module->runAction('site/error')
#1 /var/www/blog/vendor/yiisoft/yii2/base/ErrorHandler.php(111):
yii\web\ErrorHandler->renderException(Object(yii\web\NotFoundHttpException))
#2 [internal function]: yii\base\ErrorHandler-
>handleException(Object(yii\web\NotFoundHttpException))
#3 {main}
Previous exception:
exception 'yii\base\InvalidRouteException' with message 'Unable to resolve the request "post/index".' in
/var/www/blog/vendor/yiisoft/yii2/base/Module.php:532
Stack trace:
#0 /var/www/blog/vendor/yiisoft/yii2/web/Application.php(102):
yii\base\Module->runAction('post/index', Array)
#1 /var/www/blog/vendor/yiisoft/yii2/base/Application.php(380):
yii\web\Application->handleRequest(Object(yii\web\Request))
#2 /var/www/blog/backend/web/index.php(18): yii\base\Application->run()
#3 {main}
Next exception 'yii\web\NotFoundHttpException' with message 'Page not
found.' in /var/www/blog/vendor/yiisoft/yii2/web/Application.php:114
Stack trace:
#0 /var/www/blog/vendor/yiisoft/yii2/base/Application.php(380):
yii\web\Application->handleRequest(Object(yii\web\Request))
#1 /var/www/blog/backend/web/index.php(18): yii\base\Application->run()
#2 {main}
i'm pretty late to the party
but i got a few bones to pick with this solution provided.. so here it goes:
you mention you have different front and back configurations
so you are serving different folders for yii.com/:80 and yii.com/:81 respectively /frontend/web and /backend/web.
keeping this in mind,
no amount of aliases can make content of one of them available to the other.
the yii-advanced-app has #frontend and #backend aliases defined in common/config/bootstrap
Yii::setAlias('#common', dirname(__DIR__));
Yii::setAlias('#frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('#backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('#console', dirname(dirname(__DIR__)) . '/console');
DO NOT CHANGE THESE unless you know very well what you're doing.
Yii is using these aliases to autoload classes defined under these namespaces common, frontend, backend and console. this exact thing is causing the ridiculous chain of "errors occurring while handling other errors"
more details on Yii autloading documentaion
you can simply share content of these folders by creating a symlink from frontend/web/uploads to backend/web/uploads.
your webserver config (or .htaccess) will require the +FollowSymLinks option
Yii can manage this if you add a few lines to the environments/index.php file
'Development' => [
// .. other options
'setWritable' => [
// .. leave the default stuff there
'frontend/web/uploads',
],
'createSymlink' => [
// link => real folder
'backend/web/uploads' => 'frontend/web/uploads',
]
],
'Production' => [
// ..
'setWritable' => [
// ..
'frontend/web/uploads',
],
'createSymlink' => [
// link => real folder
'backend/web/uploads' => 'frontend/web/uploads',
]
],
and then run the init command again, just like in the installation guide (you do have to option to not overwrite local config files)
if you are running under windows, this might now ask you for elevated privileges
php init
or if you chose to make the symlinks manually you can try this quick guide
you can try this solution :
Yii::setAlias('#frontend', 'http://frontend.sample.dev');
Yii::setAlias('#backend', 'http://backend.sample.dev');
and if you upload files in backend set the src parameter of image to
Yii::getAlias('#backend/path/to/your/image/file');
and if you save your files in frontend replace #backend with #frontend
create this function in components folder
namespace common\components;
use Yii;
class Helper extends \yii\web\Request {
public static function getFrontendUrl($path) {
$frontUrl = str_replace('/adminpanel', '', $path);
return $frontUrl;
}
}
and use in backend :
$path \common\components\Helper::getFrontendUrl(Yii::$app->request->baseUrl).$img;
notic: in frontend You do not need

Why does Laravel passport authorize keeps loading?

I created a basic laravel passport authentication and created callback and redirect to authorize user below is my code
Route::get('/redirect', function () {
$query = http_build_query([
'client_id' => 4,
'redirect_uri' => 'http://localhost:8000/callback',
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://localhost:8000/oauth/authorize?'.$query);
});
Route::get('/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://localhost:8000/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 4,
'client_secret' => 'MUqUFrtAx3ix84zFTxwqQXA5PQDY7SWwVFW9tCNX',
'redirect_uri' => 'http://localhost:8000/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});
I followed the steps provided on https://laravel.com/docs/5.4/passport but when i click on authorize button the page keeps loading without any response and i have to restart artisan serve. What could be the possible issue?
The issue is when using php artisan serve, it uses a PHP server which is single-threaded.
The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked.
You can do this solution:
When making calls to itself the thread blocked waiting for its own reply. The solution is to either seperate the providing application and consuming application into their own instance or to run it on a multi-threaded webserver such as Apache or nginx.
Or if you are looking for a quick fix to test your updates - you can get this done by opening up two command prompts. The first would be running php artisan serve (locally my default port is 8000 and you would be running your site on http://localhost:8000). The second would run php artisan serve --port 8001.
Then you would update your post request to:
$response = $http->post('http://localhost:8001/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => 4,
'client_secret' => 'MUqUFrtAx3ix84zFTxwqQXA5PQDY7SWwVFW9tCNX',
'redirect_uri' => 'http://localhost:8000/callback',
'code' => $request->code,
],
]);
This should help during your testing until you are able to everything on server or a local virtual host.
In your /redirect route you are providing same localhost:8000 . change your redirect_uri and same mistake in callback route .
Change Your
'redirect_uri' => 'http://localhost:8000/callback',
To
'redirect_uri' => 'http://localhost:8001/callback',
Note: Im running other project on port 8001 .you can change it with yours :)
try to use XAMPP or another web server instead of just php artisan serve

How to create and use environment variable .env yii2

I want to create a file .env:
FACEBOOK_CLIENT_ID=*****
FACEBOOK_CLIENT_SECRET=*****
and use variable for config
'facebook' => [
'class' => 'yii\authclient\clients\Facebook',
'clientId' => env('FACEBOOK_CLIENT_ID'),
'clientSecret' => env('FACEBOOK_CLIENT_SECRET'),
],
I have found the solution.
I use package vlucas/phpdotenv.
Thank for all
You can archive this by Utilizing the enviroment constants. If you are using Yii2 advanced when you initialize your application as dev or production yii sets a constant YII_ENV as either dev or production in your index.php entry script.
If you are using yii basic you can set it as per your enviroment. For example we want to define config for dev.
We will proceed and edit our /web/index.php to
defined('YII_ENV') or define('YII_ENV', 'dev');
Then in our config file we would have the following
'facebook' => [
'class' => 'dektrium\user\clients\Facebook',
'clientId' => (YII_ENV_DEV ? 'Your key when in developent' : 'Your Key if not in developement'),
'clientSecret' => (YII_ENV_DEV ? 'Your key when in developent' : 'Your Key if not in developement'),
],
Refere to this for more details on Enviroment Constants http://www.yiiframework.com/doc-2.0/guide-concept-configurations.html#environment-constants
There's a package for Yii2 you can use for dotenv
https://github.com/yiithings/yii2-dotenv
Install:
composer require --prefer-dist yiithings/yii2-dotenv "*"
Usage:
Create a .env in project root directory
DB_HOST="localhost"
DB_NAME="yii2basic"
DB_USER="root"
DB_PASS="YourPassword"
config/db.php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host='. env('DB_HOST') .';dbname='. env('DB_NAME'),
'username' => env('DB_USER'),
'password' => env('DB_PASS'),
'charset' => 'utf8',
];
You could use the dotenv package offered by Symfony. https://symfony.com/doc/current/components/dotenv.html
using it in a PHP file.
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(__DIR__.'/.env');
// You can also load several files
$dotenv->load(__DIR__.'/.env', __DIR__.'/.env.dev');
.env file
DB_USER=root
DB_PASS=pass
accessing the variables from the .env file
$dbUser = $_ENV['DB_USER'];
// you can also use ``$_SERVER``

Yii2 - Gii extension assets folder alias referencing to a wrong path

I am trying to learn Yii 2 from a book (Web application development with Yii2 and PHP). Somewhere along the line it instructs me to install gii and create crud files with it.
When I installed with the following command:
php composer.phar require --prefer-dist "yiisoft/yii2-gii:*"
I have following error:
Invalid Parameter – yii\base\InvalidParamException
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
My bootstrap code:
//Define Yii debug mode
define (YII_DEBUG, true);
//Including composer autoloader
require (__DIR__ . '/../vendor/autoload.php');
//Including Yii framework
require (__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
//debugging for PHP
ini_set('display_errors', true);
//Getting Configuration
$config = require(__DIR__ . '/../config/web.php');
//Include and launch application
(new yii\web\Application($config))->run();
config file:
return [
'id' => 'crmapp',
'basePath' => realpath(__DIR__ . '/../'),
'components' => [
'request' => [
'cookieValidationKey' => 'your secret key here'
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false
],
'db' => require(__DIR__ . '/db.php')
],
'modules' => [
'gii' => [
'class' => 'yii\gii\Module',
'allowedIPs' => ['192.168.33.1']
]
],
'extensions' => [
require (__DIR__ . '/../vendor/yiisoft/extensions.php')
]
];
extensions file:
$vendorDir = dirname(__DIR__);
return array (
'yiisoft/yii2-bootstrap' =>
array (
'name' => 'yiisoft/yii2-bootstrap',
'version' => '2.0.5.0',
'alias' =>
array (
'#yii/bootstrap' => $vendorDir . '/yiisoft/yii2-bootstrap',
),
),
'yiisoft/yii2-gii' =>
array (
'name' => 'yiisoft/yii2-gii',
'version' => '2.0.4.0',
'alias' =>
array (
'#yii/gii' => $vendorDir . '/yiisoft/yii2-gii',
),
),
);
I digged it a little bit. It seems problem is about the alias of the assets folder.
In GiiAsset.php file, there is this codeblock:
...
class GiiAsset extends AssetBundle
{
public $sourcePath = '#yii/gii/assets';
...
which returns
/var/projectsRoot/crmapp/src/vendor/yiisoft/yii2/gii/assets
but it normally should return
/var/projectsRoot/crmapp/src/vendor/yiisoft/gii/assets
so it is adding an unnecessary yii2 to the path.
I tried to change the $sourcePath in extensions.php file, but changing the value here does not effect the result in any way.
Any ideas?
--UPDATE--
While I was fiddling with things, I tried to define the alias to force the correct value; as follows:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gii');
when I try to run the application with this setting I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/bower/bootstrap/dist
When I change the alias definition to this:
Yii::setAlias('#yii/gii', $vendorDir . '/yiisoft/yii2-gi');
I get following error:
The file or directory to be published does not exist: /var/projectsRoot/crmapp/src/vendor/yiisoft/yii2-gi
I'm quite confused with this behavior. What would be causing this?
I ended up with deleting my vendor folder and composer.json file, and creating it back with following content:
{
"require": {
"codeception/codeception": "*",
"fzaninotto/faker": "*",
"yiisoft/yii2": "*",
"yiisoft/yii2-gii": "*"
}
}
When I launched the gii, it again threw the following exception:
The file or directory to be published does not exist:
/var/projectsRoot/crmapp/src/vendor/bower/jquery/dist
I renamed the vendor/bower-asset folder to vendor/bower and it works now.
I probably messed up with something before without noticing, but I'm not certain why it is looking for bower, instead of bower-asset. Renaming the bower-asset to bower seems to solve it.
UPDATE
Thanks to jacmoe from the original Yii forum, it has finally solved.
It seems these two lines need do be present in composer.json in order to automatically create bower folder, instead of bower-asset.
"extra": {
"asset-installer-paths": {
"npm-asset-library": "vendor/npm",
"bower-asset-library": "vendor/bower"
}
}
Original conversation can be found at here:
These lines are automatically created when you install the basic application template, but when installing the bare code base, you need to manually write them.
I have similar problem with my app based on yii2-app-advanced, but separated from #common. Solution is just add vendorPath attribute to application config.