Data getting lost while passing from controller to view in Laravel - 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.

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

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();

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 storing mass assignment model and relationship

I'm unsure of the best practice when inserting mass assignment relationships within Laravel 5.4 - I'm new to the framework. The below code is working correctly, however can you tell me is there a way to simply into one line (inserting relationships)?
I've tried to look at 'save()'and 'push()' but it's not working as expected. Would this have an impact if transactions would scale up?
I have a Listing model, with a hasOne relationship:
public function garage()
{
return $this->hasOne('App\Garage', 'post_id');
}
First of all I have some validation, then I use the following to store, which I want to simplify to one one line of code:
public function store(Request $request)
{
// Validation has passed, insert data into database
$listing = Listing::create($request->all());
$listing->Garage()->create($request->all());
}
Also if I wanted to return the data inserted, how would I do this as the following is only returning the Listing model and not the Garage relationship? Yes I know that I wouldn't do this in a real world application.
return \Response::json([
'message' => 'Post Created Succesfully',
'data' => $listing
]);
Any help is muchly appreciated
Method chaining
Your store method looks good. You could chain methods though, if you don't need the listing object itself:
public function store(Request $request)
{
// Validation has passed, insert data into database
$garage = Listing::create($request->all())
->garage()->create($request->all();
}
But if you need the listing object, it's fine as you did it before!
Returning relation models
If you want to return the garage relation model too, you can simply do that by accessing it like a normal class propery:
return \Response::json([
'message' => 'Post Created Succesfully',
'data' => [$listing, $listing->garage]
//Access collection of garage relation ship
]);

Model returns relation´s dynamic attributes but null relation

I have set 2 models (Post and Category) with it´s proper relationships configured
class Post extends Model
{
protected $fillable = [
'title',
'excerpt',
'body',
'featured',
'published',
'category_id',
];
public function category()
{
return $this->belongsTo('App\Category');
}
}
class Category extends Model
{
protected $fillable = [
'name',
];
public function posts()
{
return $this->hasMany('App\Post');
}
}
And my Post´s storing method is
public function store(Request $request)
{
$post = Post::create($request->all());
return redirect('admin/posts');
}
The thing is, it´s actually working ok, it sets the category_id on the table and I can fetch all the dynamic data by using $post->category->name, but when I var_dump($post->relation) I get a null return.
I if create a new Post model, set all the attributes, save it and then associate the Category model (as documented on the official channel), it will return everything as expected.
For now, all I need is to fetch it´s dynamic attributes, and it´s working fine now, but I know I must be doing something wrong to get the null response. My concern is that it may be working fine now, but when the project gets larger I´ll probably face a bigger problem and I´ll have a lot of work to fix this issue.
The relation isn't there because you haven't loaded it. All it knows is the foreign key. It would be wildly inefficient if it grabbed all that information for you because it wouldn't always need all that. Think of instances where a single model could have many relationships, that would be many database calls for no reason.
If you need the relation, you can use $post->category. Since the relation is not yet loaded, it will get it for you when you do this.
Or you can eager load it by using the following $post->load('category') although this doesn't really benefit you because you are working with a single Post at this point. If you had a collection of Post objects, then you'd start seeing the benefits of using $posts->load('category') otherwise you end up with the n + 1 problem.
Consequently, if you use $post->load('category') and then var_dump($post), you should see that the relation is no longer null.

Resources