i am using laravel 5.3
Session not storing in controllers class method
I think the problem is with connect to api. after connect to api session not work
`
namespace App\Http\Controllers;
use App\GlosbeTranslate as Translate;
use Illuminate\Http\Request;
class translateLocal extends Controller
{
public $arrayDefine;
public function translate($word){
//connect to glosbe Api to translate from eng to fas
$glosbe = new Translate("eng", "fas");
$glosb=$glosbe->translate($word);
$result=json_decode($glosb);
//store result of glosbe api in array
foreach ($result->tuc as $key=>$value){
if(isset($value->phrase)){
$translate[]=$value->phrase->text;
}else{break;};
}
$sortedArray=$this->sort($translate);
$encodearray=json_encode($sortedArray,JSON_UNESCAPED_UNICODE);
//save in session
session(['name' => $encodearray]);
return $encodearray;
}
public function sort($translate){
usort($translate,function ($a,$b){
return strlen($a)-strlen($b);
});
return $translate;
}
}
// my web.php
Route::get('glosb/{word}', 'translateLocal#translate');
Route::get('/session', function () {
echo session('name');
});
when i load mysite.dev/session it's not show my session.
how can i solve that?
Can you give it a try?
Change
use App\putSession;
to
use Session;
You should update your code like:
use Session;
session(['name' => $encodearray]);
TO
Session::put('name',$encodearray]);
and change your route /session like:
Route::get('/session', function () {
$name = Session::get('name');
echo $name;
OR
echo session('name');
});
Related
I need to save the model id that is being saved and avoid another save while it's saving it, but I don't know how to persist data between requests and access it later.
JAVASCRIPT
Works perfectly well, but I can't do the same in LARAVEL 9.
// MODELS THAT ARE BEING UPDATED.
const models = {}
function handleRequest(req) {
if (models[req.model_id]) {
return
}
models[req.model_id] = true
// UPDATE MODEL.
models[req.model_id] = false
}
LARAVEL 9
Doesn't work as expected.
<?php
use App\Http\Controllers\Controller;
// MODELS THAT ARE BEING UPDATED.
$models = [];
class MyController extends Controller
{
public function index(Request $request)
{
if ($models[$model_id]) {
return;
}
$models[$model_id] = true;
// UPDATE MODEL.
$models[$model_id] = false;
}
}
Your problem is that you are trying to compare different entities in JS, you use a Function, and in Laravel you have a Class, these are different concepts and mechanics of work
You can make a property inside a class
<?php
use App\Http\Controllers\Controller;
class MyController extends Controller
{
// MODELS THAT ARE BEING UPDATED.
public $models = [];
public function index(Request $request)
{
if ($this->models[$model_id]) {
return;
}
$this->models[$model_id] = true;
// UPDATE MODEL.
$this->models[$model_id] = false;
}
}
You might consider using sessions:
session(['model_id' => 123]); // save data to session
$model_id = session('model_id'); // get data from session
I am writing a controller in which I would like to get the refresh token id but I just cannot figure out how to do it in laravel.
There are no problems with decrypting the access token. I am using standard protocol and receive data using the public key of the passport.
i tried different ways.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class RefreshTokenController extends Controller
{
public static $public_key;
public static function refresh_token(Request $request)
{
self::$public_key = file_get_contents(storage_path() . DIRECTORY_SEPARATOR . 'oauth-public.key');
$refresh_token = $request->get('refresh_token');
$data = base64_decode($refresh_token);
$public_key = openssl_get_publickey(self::$public_key);
openssl_public_decrypt($data, $decrypted, $public_key);
dd($decrypted);
}
}
I tried also standard decrypt();. But it gives an error too.
Example of incoming data.
def50200dc11ab81fdb16530806530f85fe41f7facc934447589b3a0daa202d56f5b4a8265db94b418e09280bcc8a05c88c3817612200d3c28de15c9adfd4a213f7cb136fca6f78099d686fce8d5ddf93f9bb29c1df081d7f7b75394875b5287a7ca5d9ca5eb513ea13a26195aeda41c897832467ec1b0348cdb3e5ed9476e5e7d8712b8628c18ee8ffb525de965faeb3f25b1a8eb4ee904a15341650fe6d3ed901600beda0f80c71b9b607f3e549ba8fbd9eda0e02fc7647ab8b4ea9161f7eb65833bfe46fb7f3e116a207282f947660ead392dc78ad2b9501331b4d28433a421a4193484e113baf8050d3878bd94b6ac860a1a766e79877f1af8d3ab5aee3779bf33c2a7e347552e51bb8b5448585435ef7b79d06853bcd775ce781b8d2e56289dbc8d4a10ec507aecde19bb496e90f88a687ee9bb33755046d50f860f7723d87bd4c079cd4d1242903bdb3ca447ce6ab03f2fd800182d0d8c5a3b7de5402ba2ecb4058d458cbee94da433635877e63120d6418e51eafdfd763191fceef399c16c088e27da9ffbf9
according to oauth_refresh_tokens table. All refresh token IDs are preserved. When calling the refresh token method, according to the refresh token, the corresponding access token matches in the database and is renewed.
I will be grateful for solutions.
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Defuse\Crypto\Crypto;
use Exception;
use Illuminate\Http\Request;
class RefreshTokenController extends Controller
{
public static function refresh_token(Request $request)
{
$refresh_token = $request->get('refresh_token');
$app_key = env('APP_KEY');
$enc_key = base64_decode(substr($app_key, 7));
try {
$crypto = Crypto::decryptWithPassword($refresh_token, $enc_key);
} catch (Exception $exception){
return $exception;
}
return json_decode($crypto, true);
}
}
Laravel Passport encrypts the password using the APP_ located in the ENV file.
Using the library Defuse\Crypto\Crypto;
I am new to Laravel. I have some functions in PaymentController. I want to call those functions from SmartpaySController. Here is the function which is available in PaymentController. Help me to call that function by staying in SmartpaySController.
public function getPaymentFailed($paymentId) {
$transactionData = $this->paymentRepo->find($paymentId);
if($transactionData) {
$data['quote'] = $this->quoteRepo->getQuoteById($transactionData->quote_id);
$data['metaTitle'] = 'Payment failed';
$data['returnMessage'] = $transactionData->return_message;
return view('payment::payment.quote_payment_failed', $data);
}
}
Thank you.
Instead of calling controller methods, the better practice is that you can create traits like: app/Traits and extend in controller
//trait
trait traitName {
public function getData() {
// .....
}
}
//Controller
class ControlelrName extends Controller {
use TraitName;
}
I recomend you to not call functions from one controller to another.
Make Helpers, Resources or implement same feature in other way
Never use controllers as object
But if you want to do it anyway you can use:
SomeController.php
class SomeController extend Controller {
public function someFunction(Request $request) {
// Here Some Code
}
}
YourController.php
use SomeController;
...
public function getPaymentFailed(Request $request, $paymentId) {
$controller_data = (new SomeController)->someFunction($request);
$transactionData = $this->paymentRepo->find($paymentId);
if($transactionData) {
$data['quote'] = $this->quoteRepo->getQuoteById($transactionData->quote_id);
$data['metaTitle'] = 'Payment failed';
$data['returnMessage'] = $transactionData->return_message;
return view('payment::payment.quote_payment_failed', $data);
}
}
Change:
public function getPaymentFailed($paymentId)
to:
public static function getPaymentFailed($paymentId)
This will make it staticly available in your SmartpaySController by doing:
PaymentController::getPaymentFailed($paymentId);
You can make use of Real-Time Facades
Using real-time facades, you may treat any class in your application
as if it were a facade.
To generate a real-time facade, prefix the namespace of the imported
class with Facades:
//...
use use Facades\App\Http\Controllers\SomeController;
//...
return SomeController::getPaymentFailed($request, $paymentId);
I am trying to use the native buttons and questions feature in Botman inside laravel, however i am struggling to understand how to chain functions without using static functions. I have it working where everything is a static function, however i want to use all the information gathered to send an email.
// initialization function
public function handle()
{
$botman->hears("{message}", function($botman, $message) {
$this->selectHelpQuery($botman);
});
}
// ask question function
public function selectHelpQuery($botman)
{
$question = Question::create("How can i help you, would you like to know about the following:")
->fallback("Unable to help at this time, please try again later")
->callbackId("choose_query")
->addButtons([
Button::create("button1")->value("val1"),
Button::create("button2")->value("val2"),
]);
$botman->ask($question, function (Answer $answer, $botman) {
// Detect if button was clicked:
if ($answer->isInteractiveMessageReply()) {
if($answer->getValue() == "val1")
{
$this->contactFollowUp($botman); //** not working
} else {
$this->contactNoFollowUp($botman); //** not working
}
}
});
}
// other functions.....
However without declaring the contactFollowUp() function as static and accessing it by using the classname BotManController::contactFollowUp($botman) However if i do this i have issues with accessing and setting data for use in other functions. Specifically i get a Method contactFollowUp does not exist error.
So, after finding some github code examples i have managed to work out the issue. It is to do with the way the botman framework is structured. To achive linked conversations you have to use a function from the botman framework called startConversation() to envoke this you need to reference bot which is from the extended base class Conversation. So you will need an entry point and then the conversation you want to link to like so:
*note you will need the default entry point of run() for each conversation.
//BotManController.php
<?php
namespace App\Http\Controllers\Chatbot;
use App\Http\Controllers\Controller;
use BotMan\BotMan\BotMan;
use Illuminate\Http\Request;
use BotMan\BotMan\Messages\Incoming\Answer;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use BotMan\BotMan\Messages\Outgoing\Question;
class BotManController extends Controller
{
/**
* start the conversation on intitlization
*/
public function handle()
{
$botman = app("botman");
$botman->hears("{message}", function($botman, $message) {
$botman->startConversation(new BotManStart);
});
$botman->listen();
}
}
Then
// BotManStart.php
<?php
namespace App\Http\Controllers\Chatbot;
use BotMan\BotMan\BotMan;
use Illuminate\Http\Request;
use BotMan\BotMan\Messages\Incoming\Answer;
use BotMan\BotMan\Messages\Outgoing\Actions\Button;
use BotMan\BotMan\Messages\Outgoing\Question;
use BotMan\BotMan\Messages\Conversations\Conversation;
class BotManStart extends Conversation
{
public function run()
{
$this->selectHelpQuery();
}
public function selectHelpQuery()
{
$question = Question::create("How can i help you, would you like to know about the following: ")
->fallback("Unable to help at this time, please try again later")
->callbackId("choose_query")
->addButtons([
Button::create("Button 1")->value("button1"),
Button::create("Button 2")->value("button2"),
]);
$this->ask($question, function (Answer $answer) {
if ($answer->isInteractiveMessageReply()) {
switch ($answer->getValue()) {
case "button1":
$this->bot->startConversation(new BotManConversation1());
break;
case "button2":
$this->bot->startConversation(new BotManConversation2());
break;
}
}
});
}
}
I've been reading the documentation up and down now, still not sure what I'm doing wrong. In my opinion the documentation is very difficult to understand for a beginner.
Anyway, I'm trying to make something akin to the Auth::user() method, where it returns additional data about a logged in user that I will be needing for this application.
I have this helper class here:
namespace App\Helpers;
use Auth;
use Illuminate\Http\Request;
use App\Models\Grouping\User;
use App\Models\Grouping\Client;
use App\Models\Grouping\Rank;
class ClientUser {
public function __construct($request) {
$this->request = $request;
}
public function client() {
return Client::find($this->request->session()->get('client_id'));
}
public function auth() {
if (Auth::check()) {
// Get the client
$client = $this->client();
// Get the client's user
$user = $client->users()->find(Auth::user()['id']);
// Get the rank of the logged in user
$rank = Rank::find($user->pivot->rank_id);
return [
'user' => $user,
'rank' => $rank,
'client' => $client
];
}
return null;
}
}
This is responsible for doing what I described, returning additional data that I can't get through Auth::user(). Now I'm trying to register this class in the AuthServiceProvider
public function register()
{
// Register client auth
$request = $this->app->request;
$this->app->singleton(ClientUser::class, function ($app) {
return new ClientUser($request);
});
}
Now what I don't understand is how I'm supposed to make this globally accessible throughout my app like Auth::user() is.
The problem with just making "importing" it is that it needs the request object, which is why I'm passing it through the service container.
Now here's where I'm stuck. I'm not able to access app in my controller or anywhere, and I can't define a Facade because a Facade expects you to return a string of the bound service that it should "alias?"
Change your service provider like this :
$this->app->bind('client.user', function ($app) {
return new ClientUser($app->request);
});
Create another class extended from Illuminate\Support\Facades\Facade.
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class ClientUserFacade extends Facade {
public static function getFacadeAccessor(){
return "client.user";
}
}
Add 'ClientUser => ClientUserFacade::class in alias key of app.php