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

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;

Related

Laravel how to set a database environment variable?

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.

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;
}

Laravel Nova Observe not connecting to tenant database

I have a multi tenant App. My system database I have models- User, Billing, FrontEnd ... and using policies I'm able to show, hide and prevent viewing and actions by tenant.
Each tenant has a database with models- Member, Event, Item ...
I set each model database based on the Auth::user()->dbname in the _construct method. This allows me to set my dbname to a clients database for tech support.
class Item extendsw Model {
public function __construct() {
parent::__construct();
if(Auth::user()->dbname) {
Config::set('database.connections.tenant.database', auth()->user()->dbname);
$this->connection = 'tenant';
}
}
This all works as planned until I add and Observer for a client model e.g. Member
I now get an error on any Observer call.
Trying to get property on non object Auth::user()->dbname.
Where should I be registering the Observer? I tried AppServiceProvider and NovaServiceProvider.
I think that happens because the observer instantiates your User model before the request cycle has started and that means that your User instance does not exist yet neither has been bound in the Auth facade.
Thus, Auth::user() returns null and you are trying to get a property from it.
A way to solve the issue may be to check if the user instance exists or not:
public function __construct() {
parent::__construct();
if (optional(Auth::user())->dbname !== null) {
Config::set('database.connections.tenant.database', auth()->user()->dbname);
$this->connection = 'tenant';
}
}
The optional helper return the value of the accessed property (dbname in your case) if and only if the argument is not null, otherwise the whole call will return a null value instead throwing an exception.
If that is not the case, maybe update the question with the error stacktrack and the code/action that triggers the error

Save complete model in session - Codeigniter

I want to save complete model in session, so I can use data easily in entire application.
After successful login in application I am saving model in session and session save in database in ci_session table.
Code I tried:
$loginSuccess = $this->login_model->doLogin($username, $password);
if($loginSuccess) {
$this->login_model->initialize(); // this will set value in private variable
$serializelogin = serialize($this->login_model);
$this->session->set_userdata('userprofile', $serializelogin);
}
This code gives me an error:
Error Number: 2006
MySQL server has gone away
Update: I change user_data column of table ci_session from text to longtext
U need to start by creating a session.
//Destroy old session
$this->session->sess_destroy();
//Create a fresh, brand new session
$this->session->sess_create();
//Set session data
$this->session->set_userdata($row);
Basically $row is an array.
$row = $serializelogin->row_array();
or
$this->session->set_userdata(array('active_flag' => false, 'active_status' => 0));
make sure the data which has been returned from the model is in row_array format.

Laravel How to store extra data/value in session Laravel

I'm using default auth() in laravel login (email & password)
Now i try to take input from the user in text field like (Age or City)
Now i want to store (Age/City) in my session.
Help me
You can use session() helper:
session('age', 18); // saves age into session
$age = session('age')`; // gets age from session
Update
If you want to save Age and City after user registration, you should store this data in a DB, not in a session. You can add some fileds in create method of app\Http\Controllers\Auth\AuthController.php
You can use
Session::put('key', 'value');
To get key from Session use
Session::get('key');
You can use the session() helper function as #Alexey Mezenin answer.
Laravel Session Documentation
Ok let me enlighten you. if you want to store it in session do it this way.
session('country', $user->country); // save
$country = session('country')`; // retrieve
But that is not the way we do in Laravel like frameworks, it uses models
once the user is authenticated each time when we refresh the page, application looks for the database users table whether the user exists in the table. the authenticated user model is a user model too. so through it we can extract any column. first thing is add extra fields to the User class(Model) $fillable array.
so it would look something like this.
User.php
protected $fillable = ['username', 'password', 'remember_token', 'country'];
so after simply logging in with user name and password in anywhere just use Request class or Auth facade. Facades are not too recommended so here for your good as a new one i would just say how to use Request. Suppose you want to retrieve your Authenticated user country inside TestController.php here is how it could be used in the methods.
TestController.php
use Illuminate\Http\Request;
public function testMethod(Request $request)
{
$someCountry = $request->user()->country; //gets the logged in user country
dd($someCountry); //dd is die and dump, could be used for debugging purposes like var_dump() method
}
Using Request
public function ControllerName (Request $request){
$request->session()->put('session_age', $age);
}
Get session_age
$get_session_age = $request->session()->get('session_age');
Using Session
public function ControllerName (){
Session::put('age',$age);
}
Get the session
$session_age = Session::get('age');
Don't forget to define Session or Request in your controller!!!
use App\Http\Requests;
use Session;
To work with session in your controller you need to include session first in your controller
use Session;
After that for store data in session. There is several ways to do it. I prefer this one (in controller)
session()->put('key',$value);
To display session data in your View you can do it like this
#if(Session::has('key'))
I'v got session data
#else
I don't have session data
#endif
To get session data in your Controller you can do it like this
session()->get('key')
//or
session()->get('key','defaul_value_if_session_dont_exist')
When you are done with your data in session you can delete it like this (in controller)
session()->forget('key');
All this basic usage of session is well documented in official Laravel documentation here.
Hope it helps you

Resources