save collection in global variable in laravel 5.6 - laravel

so basically i have an index page where i have to go to controller to fetch data from database
route:-
route::get('/index/{$x}', 'indexController#index');
index controller:-
$data = Data::where('name', $x)->get();
return View::make('index', compact('data');
then inside index page i have link that goes to second page
with same data, i d not want to query the same data as it may affect performance
route:-
route::get('/second', indexController#second);});
Second Controller:-
$data = $data->sortBy('id');
return View::make('second', compact('data');
i thought of saving data in global variable in controller
so i added private variable inside controller and try to access it through $this->data
but it did not work cause based on my search the controller will be closed after it returns view
so if i try access $this->data inside second function it will be empty
is it possible to save queried data (collection) in global variable
as i do not want to query same data for every page
your help will be appreciated

If you having same data on different pages that will not be solved using any kind of global variables. You need to cache query results. Please check cache in laravel docs https://laravel.com/docs/5.6/cache
Here is how that is usually done:
$data = Cache::get('some_cache_key');
if (empty($data)) {
$data = Data::where('name', $x)->get();
Cache::put('some_cache_key', $data, 60); //60 minutes
}
return View::make('index', compact('data');

There are multiple ways to achieve this. Either you can store the data in the Session and access all across the application
$data = Data::where('name', $x)->get();
session()->put('data', $data);
You can also use View::share('key', $data)
In your AppServiceProvider inside boot() method
public function boot()
{
View::share('data', Cache::get('data'));
}
In your controller.
$data = Data::where('name', $x)->get();
Cache::put('data', $data);
By this way you can access the data all across the application using {{ $data }} in your views.
hope this helps.

Related

Laravel 6, passing multiple arrays from a controller to a view

I'm brand new to Laravel, I need to display around 8 different drop down menus on a page all populated from tables in my Db, I am using blades.
In my controller I can create various types of arraysin one function (using eloquent) and I can dd(); them out correctly one at a time, my issue appears to be that you can only pass one array through a controller to a view. I have tried various options I found here but without success, including ->with and compact(). I have tried defining the arrays in the controller one at a time and passing them using compact() all result in errors either the variable not defined or trying to get an non-object. I am obviously going about this all wrong any help would be great.
This is not a code issue (hence no code posted) I think it more of a Laravel issue that I don't yet understand, thanks in advance.
Try like this
class YourController extends Controller{
public function yourMethod(){
$arr1 = [];
$arr2 = [];
return view('view.name', ['arr1' => $arr1, 'arr2' => $arr2]);
}
}
If you have:
$array1 = [...];
$array2 = [...];
Then you can:
return view('path.to.view', compact('array1', 'array2');
This is my route from web.php and my controller from ReservationContoller any help as to my the arrays wont pass would be great, many thanks.
Route::get('/client/{client}/reservation/{reservation}', 'ReservationController#getReservation');
public function getReservation($client, $reservation)
{
$client = Client::findOrFail($client);
$reservation = Reservation::where('client_id', $client->id)->get();
$company = Company::where('type', 'staghen')
->where('status', 'Active')
->orderBy('comp_name')
->pluck('comp_name', 'id');
$cl = array(['client' => $client]);
$res = array(['reservation' => $reservation]);
$comp = array(['company' => $company]);
return view('admin.reservations.reservation', compact('$cl', '$res', '$comp'));
}

How to handle json request in laravel controller?

I'm using JSON request to get nation detail in my view, here is how I am doing it;
Controller:
public function ajaxrequest(Request $request)
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations);
}
now I want to access data from Area table, I will have to create another controller? or I can add that in the above controller? I have 10 different tables like nation from where I want to get data through JSON. but I am not sure whether I can do everything in a single controller.
It all depends how do you want to access data and yes you can fetch data from one controller only if it's needed.
Also you can check it based on the request
EXAMPLE :
public function ajaxrequest(Request $request)
{
$check = $request->get('something_to_check");
if($check){
$data = Table1::all()->pluck('id');
}else{
$data = Table2::all()->pluck('id');
}
return response()->json([
'data' => $data,
//...
]);
}
Like #ViperTecPro mentioned, you can access multiple tables from the same method in a controller but if possible you should have separate endpoints for each case to you get rid of multiple if checks.
Just a thought.

how to display name from database in laravel

i want to display data from my database
controller
public function generatePDF(Request $request)
{
$id = Auth::user()->id;
$name = User::select("NAME")->where("id", $id)->get();
$pdf = PDF::loadView('generatePDF', ['name'=>$name]);
return $pdf->stream('generatePDF.pdf');
}
blade
<h2>{{name}}</h2>
result
[{"NAME":"name_from_database"}]
can i display without [{"name":}], so just the value of data (name_from_database) ?
Simple use find like this
$name = User::find($id)->name;
Or direct from auth
$name = \Auth::user()->name;
To get logged in user id you can use \Auth::id()
you can use:
$user_id = User::findOrFail($id)->first();
$name=$user_id->name;
test the laravel log file:
\Log::info($name);
Use first() instead of get(), because get() will return an array and first() will return the object.
DRY Code line no.1 and no.2. simple use:
$name = auth()->user()->name;
to get the name of the currently authenticated user.
Send $name to you view is fine
$pdf = PDF::loadView('generatePDF', ['name' => $name]);
Correct your code in blade file
{{ name }} -> {{ $name }}
I hope this might help you. :)
Hello Aldi Rostiawan,
$nameGet = User::select("NAME")->where("id", $id)->get();
$nameFirst = User::select("NAME")->where("id", $id)->first();
Here in both line of code the difference is only Get and First.
Get method returns an Array of objects. So for example if the query apply on many records then the code will give you many objects in an array. Or if query will be true for only one record then also it will return an array with one object.
If you know that id is primary key of he table then only one record will be fetched then you can use First function instead if Get method.
First function always return an Object. In case if query apply on many records then also first method will return you only first record as an Object.
And it seems that you have required an Object only.
You should try this:
Controller
public function generatePDF(Request $request)
{
$id = Auth::user()->id;
$rsltUser = User::where("id", $id)->first();
$pdf = PDF::loadView('generatePDF', ['rsltUser'=>$rsltUser]);
return $pdf->stream('generatePDF.pdf');
}
blade
<h2>{{$rsltUser->name}}</h2>
use VALUE() to display name only.
in your case:
<h2>{{$rsltUser->value('name')}}</h2>
your name variable is an array containing a single object with a NAME attribute .. so to diplay that value, you should change your script to
<h2>{{name[0]['NAME']}}</h2>

Returning custom variable in Settings - Laravel Spark

I have setup Spark and I have created my custom view in Settings - Students (assume User object is actually a teacher). I have also created migration and model Student.
Now http://spark.app/settings/students returns the page successfully. At this point, I need to return data from backend. I investigated Spark\Http\Controllers\Settings\DashboardController#show - which is the method returning the 'settings' view, however this doesn't return any data to view using ->with('user', $user)
But, as mentioned in Docs, :user="user" :teams="teams" :current-team="currentTeam" already available out of the box.
Where and how does Spark returns these values to /settings? And How do I make my Student object available likewise?
Now, if I want to return my Student object to front-end, I have 2 choices.
1) edit Spark\Http\Controllers\Settings\DashboardController
2) I think Spark\InitialFrontendState is the place where Spark returns these objects user, teams, currentTeam. This approach is something I've seen for the first time to be honest and I didn't really understand how it works.
So how should I achieve in Spark, something as simple as :
return view('spark::settings')->with('student', $student); ?
Add a new route and set up your own Controller & own view
web.php
Route::get('/settings/students', 'SettingsStudentController#index');
SettingsStudentController.php
class SettingsStudentController extends Controller {
public function __construct() {
$this->middleware('auth');
}
public function index(Request $request) {
$user = Auth::user();
$student = STUDENTCLASS::whatever();
return view('yourstudentview', ['student' => $student , 'user' => $user]);
}
}

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.
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
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

Resources