View Share doesn't return updated data, how then to share live data? - laravel

I currently have a model which access data like so:
$currentSessionID = session()->getId();
$displayCart = Cart::where('session_id', $currentSessionID)->get();
return view('layouts.cart')->with('cartDetails', $displayCart);
This model correctly retrieves the data in a current session.
To access this same data in a header file I'm using View::Share in the AppServiceProvider like so:
public funciton boot()
{
$currentSessionID = session()->getId();
$inCartDetails = Cart::where('session_id', $currentSessionID)->get();
View::share('inCartDetails', $inCartDetails);
}
In my blade the $inCartDetails returns empty. I get [].
My suspicion is that this function ONLY gets called at boot. Hence the name :) and that it's empty cause at the time of starting the session it's empty since user hasn't selected anything. If this is correct how would I then pass live data to multiple views?

The session is not available in the boot method of the service providers. You should create a middleware for this. Check out this answer here: How to retrieve session data in service providers in laravel?

Related

Limit User See Only Their Data [ Laravel ]

I want to limit User to see only their data not Any Other data in laravel.
Ex. User A can see only data that User A was created And Cant See Any Data created by Other User.
My Controller
<pre>
public function index()
{
$expense = Expense::with(['user'])->get();
return ExpenseResource::collection($expense);
}
</pre>
Thanks in advances..
You will need to have a user_id in your expenses table then in your controller you do this
Expense::where('user_id', Auth::id())->with('user')->get();
Edit:
However you may want to check laravel's Global scope or Local scope

Yii2 how to I get user from database in findIdentityByAccessToken method?

I need to set up JWT authentication for my Yii2 app. The authentication itself works fine, the token gets parsed and I can read it's data in my User model. But the problem is that I need to compare this data to a real user in my DB. So, I've got this method in the User model which extends ActiveRecord
public static function findIdentityByAccessToken($token, $type = null) {
$user = User::findOne(['ID' => 1]);
die(json_encode($user));
}
It's very simplified just to see that it finds a user. It does not and it always returns this:
{"id":null,"userLogin":null,"userPass":null,"userNicename":null,"userEmail":null,"userUrl":null,"userRegistered":null,"userActivationKey":null,"userStatus":null,"displayName":null}
The data is not populated. But if I do the same inside any controller, like so
class TokenController extends ActiveController
{
public $modelClass = 'app\models\User';
public function actionFind(){
return User::findOne(['ID' => 1]);
}
}
It works great and I get the User object populated with correct data.
Is it possible to get user from not within an ActiveController class?
Well, I don't know exactly what is wrong with this line here die(json_encode($user));
But it actually finds and populates the user and I can access it later via
Yii::$app->user->identity
so I can also blindly compare its ID and password to the real ones here

Sharing across view in Laravel 5.4

I have a project where users are assgned to a client and I wannt to share that info across views.
In AppServiceProvider I added
use View;
use Auth;
and then amended boot to
if ( Auth::check() )
{
$cid = Auth::user()->client_id;
$company = \App\Clients::first($cid);
view::share('company',$company);
}
but if I dd($company) I get
Undefined variable: company
This is because of the Auth is not working in AppServiceProvider
So your If condition return false
if you share data with all the views then your code like this without check Auth. then It will work.
$company = 'Some value';
view::share('company',$company);
dd($company); // for print output.
Solution - For Alternate option you have to make Helper class.
At the time the providers boot is run, the Auth guard has not been booted, so Auth::check() returns false, and Auth::user() returns null.
You could do the View::share in a middleware, or perhaps in the constructor of a controller (the base controller to share it across the whole application, or some particular controller if you need it in some subset of routes).

How to add additional data to object Auth in Laravel 5.3?

There is default object Auth in Laravel after authification.
It contents data about current user from table Users.
How can I add the additional data to this object from other related table?
Edit:
So, if I am right, the object Auth is created when user is authenticated. In this moment I need to fill object by additional data.
I presume you want to retrieve a user in a controller and return it as a response, maybe json? or not, it's doesn't really matter. here what you could do
public function getUser()
{
$user = auth()->user();
$user->load('relationName');
$user->load('anotherRelationName');
}

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