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

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

Related

Why we need to create a function in model page for relation

public function single($category, $slug)
{
$category = Category::where('slug', $category)->first();
$article = Article::where('slug', $slug)->where('category_id', $category->id)->first();
$data['comments'] = Comment::where('article_id', $article->id)->get();
}
These codes are on my controller page. When I take the comments on my article page it is working fine.
But on the laravel webpage, they say we have to create function in Model. Why we need to create a function in Model page? My structure is working fine without extra function.
I will be glad if you explain, thank you.
the difference is you can do something like this with a single db query and alter the results:
public function single($category, $slug)
{
$category->where('slug', $category)->articles()->where('slug', $slug)->with('comments');
}

laravel 5.6 Eloquent : eloquent relationship model creation issue

in my controller i create an Eloquent Model Instance passign throug a relation. The model is loaded on controller's __construct, that's why is present a $this->store and not a $store.
public function index()
{
if (is_null($this->store->gallery)) {
$this->store->gallery()->create([
'title' => 'gallery_title,
'description' => 'gallery_description',
]);
}
$gallery = $this->store->gallery;
dd($gallery);
return view('modules.galleries.index', compact('gallery'));
}
Simply if a store's gallery is not present yet, let's create it.
The first time i print out my dd() is ALWAYS null, if i reload the page the dd() show correctly my gallery model.
The things is weird for me, seems like the first time the creation is done but not ready... I can work around but why this code doesn't work the first time?
Help is very appreciate.
Relationship codes: on gallery ....
public function store()
{
return $this->belongsTo(Store::class);
}
on store...
public function gallery()
{
return $this->hasOne(Gallery::class);
}
When using the $this->store->gallery()->create() method, the original method is not hydrated with the new value, you can simply do a
$gallery = $this->store->refresh()->gallery;
OR
$gallery = $this->store->load('gallery')->gallery;
if you want to make your code cleanner you can do that in your Store Model:
public function addGallery($gallery){
$this->gallery()->create($gallery);
return $this->load('gallery')->gallery;
}
And that in your controller:
$gallery = $this->store->addGallery([
'title' => 'gallery_title',
'description' => 'gallery_description',
]);
and voila ! You have your gallery ready to be used :)
It's the lazy load part of Eloquent. basicly, when you tested for it with is_null($this->store->gallery) it sets it to that value.
when you tried to recover it again, it did not do the DB query, it just loaded the value already present (null).
after creation you need to force reload the relation:
$this->store->load('gallery');
or
unset($this->store->gallery);
or
$gallery = $this->store->gallery()->get();

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>

save collection in global variable in laravel 5.6

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.

Data getting lost while passing from controller to view in Laravel

In one of my controller, I'm passing the result obtained from an Eloquent query to a view. But no matter how I pass the result to the view, I'm not getting the result in the view.
The controller:
class ProductCategoriesController extends BaseController
{
public function __construct()
{
parent::__construct();
// Add location hinting for views
View::addNamespace('product-categories', app_path() . "/MyVendor/ProductsManager/Views/admin/product-categories");
}
public function index()
{
$categories = ProductCategory::all();
return View::make('product-categories::index')
->with('title', 'All Product Categories')
->with('categories', $categories);
}
...
}
If I view the dd the value of $categories inside the index controller, I get the proper Eloquent collection, like following:
object(Illuminate\Database\Eloquent\Collection)[655]
protected 'items' =>
array (size=1)
0 =>
object(MyVendor\ProductsManager\Models\ProductCategory)[653]
protected 'table' => string 'product_categories' (length=18)
protected 'guarded' => ...
But if I dd the value of $categories inside the index view, I get an empty Eloquent collection, like following:
object(Illuminate\Database\Eloquent\Collection)[655]
protected 'items' =>
array (size=1)
0 => null
I am doing similar approach in other controllers and they work fine. I don't know what the problem with this controller is. I have been using Laravel for quite some time now and never had this problem before. Maybe I'm missing something, or there's something wrong with the recent package updates. Whatever it is, it's driving me crazy. Any ideas on what the problem might be?
P.S. I'm using Laravel Framework version 4.2.6
I finally figured out what the problem was. I was using robclancy/presenter package to wrap and render objects in the view. For it, the model had to implement a PresentableInterface interface. Implementing the interface required the method to have a getPresenter method. I had added the getPresenter method in my model, but I forgot to return the presenter from that method. Returning the presenter solved the problem.
The code inside the getPresenter method is the code that I forgot to write.
public function getPresenter()
{
return new ProductCategoryPresenter($this);
}
Thank you guys for trying to help.

Resources