陳佩裘
陳佩裘

Reputation: 137

Laravel 5.4 - I can't use static array to save data in controller. How to deal with it?

I want to keep some data from every request but I don't want to use database , because these data just keep temporary , so...I use a static array in my controller,

public static $aId = [];

and when request come in , I take the data and push it to that array , just like

public function saveId(Request $request){
   $id = $request->id;
   array_push(MyController::$aId,$id);
   return var_dump(MyController::$aId);
}

But problem is , every request will make that array become a new array , I always get an array which only have one data. Please help me.

Upvotes: 1

Views: 315

Answers (2)

user320487
user320487

Reputation:

Either the cache or session would work for you. Create a unique key, such as

$key = Auth::user()->id . '-aId';

Cache::put($key, $id, Carbon::now()->addMinutes(10));

or

Session::put($key, $id);

and reference that between requests. The user id will not change and the -aId suffix will allow you to keep what you have in the session already.

edit ok so you want it globally available across all users, sessions, etc...

// assuming an array has already been set in cache key 'request-ids'...
$id = $request->id;
Cache::forever('request-ids', array_push($id,Cache::get('request-ids')));

https://laracasts.com/discuss/channels/laravel/is-it-possible-to-share-cache-between-users

Upvotes: 0

Tom
Tom

Reputation: 990

Use the session to persist data over multiple requests.

public function saveId(Request $request){
   $id = $request->id;
   $request->session()->push('aId', $id');
   return print_r($request->session()->get('aId'), true);
}

More information: https://laravel.com/docs/5.4/session

Upvotes: 1

Related Questions