Laravel how to set a database environment variable? - laravel

I need to set a variable in my database every time a connection is opened, get a variable from the token and set the user
SET app_user_id = Auth::id() ?? null;
what is the correct place to set this variable, would be in the AppServiceProvider?

You can do that with DB::statement. Auth::id() returns null if there is no authenticated user in the default guard, so ?? null is unnecessary.
Putting it in a service provider might work.
public function boot()
{
DB::statement('SET app_user_id = ?', [Auth::id()]);
}
However, I don't think this will work as you expect it to.
Every user is connecting to the same database and the app_user_id value will be overwritten.

Related

use laravel session value from function to another in the same controller in api or web route

When i'm trying to set session value in function then using this value it's fine but when i'm trying to reuse the same value which saved in the session with it's key i got undefined key in the array of the session why that's happen and how to handle that i tried to set middleware in the route but it gave me the same error
note: i redirect from my domain to another domain i know that's the problem occur after redirecting how to handle that i need standard solution i used $_cookie and it's worked but i want to use session ???
I'm tring to use the session values from function to another in the same controller after redirecting to another domain and back to my domain can someone tell me how to handle that and you must know that i don't controll the response from the external domain and this domain don't return the data that i want ???
the question here i need session to not expired if i go to this domain then back to my domain ?
try to capture the id after the creation
public function setCaptureOrderId($id) {
Session::put('catpureId', $id);
Session::save();
}
can use this getCaptureOrderId function
public function getCaptureOrderId() {
return $_SESSION['orderID'];
}
then redirect
public function http_create(){
return Redirect::to($url);
}
finally after the redirecting
getCaptureOrderId don't return anything and undefined key

how to session()->forget('cart') for another user in laravel?

my session driver is set to database,
.env => SESSION_DRIVER=database
I have made a model for session and I access to a session of another user by user_id like this :
use App\Models\Session;
$payload = Session::where('user_id', $request->user_id)->pluck('payload');
$payload = unserialize(base64_decode($payload));
if (!isset($payload['cart'])) {
dd($payload['cart']);
}
now I want to session()->forget('cart') of that specific user not the current user, but the payload field is decode by base64 and serialized.
how to do that?
thanks
I tried a few things and by changing the id it works :
// Get the store from laravel (encrypted or not)
$store = session()->getDrivers()['database'];
// Change the id
$store->setId($id);
// Start the session
$store->start();
// Remove the item
$store->pull('cart');
// Save the session in database
$store->save();
i don't think it's something that laravel support, so this might break in the future
Yes I found it.
the problem is to displacement of serialize() and base64_encode() after unset($payload['cart']) like this:
use App\Models\Session;
$session = Session::where('user_id', $request->user_id)->first();
$payload = unserialize(base64_decode($session->payload));
if (!isset($payload['cart'])){
unset($payload['cart']);
}
$session->payload = base64_encode(serialize($payload));
$session->save();

Laravel Auth::user()->id returns 0 on custom id

I am trying to make a User object with a String as ID. Everything went fine, even authenticating. But whenever I am trying to get the currently logged in user his ID by either:
Auth::user()->id
or
Auth::id();
Both are returning '0'. Whenever I dump the Auth::user object I can actually see the id attribute correctly. Have I done something wrong?
Laravel tries to cast it to integer, simply put the following property in your User class.
class User {
public $incrementing = false;
}

I am getting an error message on my laravel app: creating default object from empty value

I want to save some values in my transaction table. I stored the value of the pharmacy in a session and now am trying to save it. This is my controller;
Public function redirectToGateway(Request $request)
{
$old cart= Session:: get('cart');
$cart=new Cart($oldCart);
session ()->put ('user_id,$request->get('user_id));
session ()->put ('pharmacy',$request->get('pharmacy'));
$id= Session:: get('user_id');
$pharmacy= Session:: get('pharmacy');
$transhistory=Transaction:: find($id);
$transhistory->pharmacy=pharmacy;
$transhistory->email=$request->get('email');
$transhistory->amount=$request->get('amount');
$transhistory->cart=serialize($cart);
$transhistory->save();
First check if the session values really exists or not and secondly this $transhistory->pharmacy=pharmacy; should be $transhistory->pharmacy=$pharmacy;

How to "Refresh" the User object in Laravel?

In Laravel you can do this:
$user = Auth::user();
Problem is, if I do changes on items on that object, it will give me what was there before my changes. How do I refresh the object to get the latest values? I.e. To force it to get the latest values from the DB?
You can update the cache object like this.
Auth::setUser($user);
for Example
$user = User::find(Auth::user()->id);
$user->name = 'New Name';
$user->save();
Auth::setUser($user);
log::error(Auth::user()->name)); // Will be 'NEW Name'
[This answer is more appropriate for newer versions of Laravel (namely Laravel 5)]
On the first call of Auth::user(), it will fetch the results from the database and store it in a variable.
But on subsequent calls it will fetch the results from the variable.
This is seen from the following code in the framemwork:
public function user()
{
...
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
...
}
Now if we make changes on the model, the changes will automatically be reflected on the object. It will NOT contain the old values. Therefore there is usually no need to re-fetch the data from the database.
However, there are certain rare circumstances where re-fetching the data from the database would be useful (e.g. making sure the database applies it's default values, or if changes have been made to the model by another request). To do this run the fresh() method like so:
Auth::user()->fresh()
Laravel does do that for you, HOWEVER, you will not see that update reflected in Auth::user() during that same request. From /Illuminate/Auth/Guard.php (located just above the code that Antonio mentions in his answer):
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method because that would tremendously slow an app.
if ( ! is_null($this->user))
{
return $this->user;
}
So if you were trying to change the users name from 'Old Name' to 'New Name':
$user = User::find(Auth::user()->id);
$user->name = 'New Name';
$user->save();
And later in the same request you try getting the name by checking Auth::user()->name, its going to give you 'Old Name'
log::error(Auth::user()->name)); // Will be 'Old Name'
A little late to the party, but this worked for me:
Auth::user()->update(array('name' => 'NewName'));
Laravel already does that for you. Every time you do Auth::user(), Laravel does
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveByID($id);
}
It nulls the current user and if it is logged, retrieve it again using the logged id stored in the session.
If it's not working as it should, you have something else in your code, which we are not seeing here, caching that user for you.

Resources