laravel 5.6 Eloquent : eloquent relationship model creation issue - laravel

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

Related

Returning a Modal with relationships after creating in Laravel

I have a modal for example User. The User has relationships to Country and Currency modal as well. I would like to return a JSON object of the User with their relationships. I can achieve that using the code below:
$user = User::create($request->all()); // request contains all the information to create the user
$userDetails = User::with('country', 'currency')->where('id', $user->id)->first();
return json_encode($userDetails);
It works. However, is there a better or more recommended way to achieve this? Thank you for your time.
I found out that creating a new Laravel Resource and using the following approach seems much cleaner:
// in UserResource.php:
public function toArray($request)
{
return [
'id' => $this->id,
'country' => $this->country, // relationship
'currency' => $this->currency // relationship
]
}
// In controller:
return new UserResource($user);
Thanks!

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

How to add data to additional column in pivot table in laravel

I'm trying to build an app in Laravel 5.3, I want to add additional column data in the pivot table. Following is my code:
My Users model:
public function relations()
{
return $this->belongsToMany('App\Plan')->withPivot('child');
}
My Plan model:
public function relations()
{
return $this->belongsToMany('App\User')->withPivot('child');
}
In my controller I'm fetching the user data from Auth::user(); and for plans and child element I'm getting through request. I want to store this to my pivot table. Following is the code which I tried in my controller:
$user = \Auth::user();
$plan_id = $request->plan_id;
$childid = $request->child_id;
$plan = App\Plan::find($plan_id);
$user->relations()->attach($plan, ['child' => $childid]);
Help me out in this.
You should use attach() like this:
$user->relations()->attach($plan_id, ['child' => $childid]);
Try the save method as:
$user->relations()->save($plan, ['child' => $childid]);
Docs
Both save and attach work. Just that attach will return null while save will return $user object when I try with tinker

exclude certain records from laravel scout/algolia

I am using laravel scout to upload records for searching in algolia. I have added the searchable trait to my model, and everything is working fine.
There is a case now where I don't want to add certain records to my index if they have set status I.E UNPUBLISHED.
is there away I can evaluate the status field and decide if I want the model to be uploaded to the index?
Just use $model_name->unsearchable() to remove it from your Algolia index.
See "Removing Records" in the documentation for more details: https://laravel.com/docs/5.3/scout#removing-records
You can use method toSearchableData() and in case the status is Unpublished, just return empty array and the record will be skipped.
Otherwise just return $this->toArray().
It will do the trick.
Say we have a Post model, with a boolean published attribute, and a model factory to seed our table as follows:
$factory->define(App\Post::class, function (Faker\Generator $faker) {
$tile = $faker->realText(50);
$date = $faker->dateTime;
return [
'title' => $tile,
'body' => $faker->realText(500),
'published' => $faker->boolean(80),
'created_at' => $date,
'updated_at' => $date
];
});
Let's say we will seed 10 records.
public function run()
{
factory(App\Article::class, 10)->create();
}
If we tried to exclude unpublished records within the toSearchableArray() method, as suggested:
public function toSearchableArray()
{
if (! $this->published) {
return[];
}
// ...
}
When seeding the posts table, instead of ignoring unpublished records by returning an empty array, scout will keep asking the model factory for a published model.
For example, if two of the seeded records were randomly unpublished, scout would index all 10 records (instead of 8) anyway, replacing the unpublished ones by a new model factory (with a published set attribute). Thus causing to have two inexistent (on our table) records in the algolia index. Quite confusing.
The "neatest" way around this I could come up with, was to listen to the saved/updated events (saving/updating won't cut it) in the model's boot method.
protected static function boot()
{
static::saved(function ($model) {
if (! $model->published) {
$model->unsearchable();
}
});
static::updated(function ($model) {
if (! $model->published) {
$model->unsearchable();
}
});
parent::boot();
}
Check out this question. This problem has been solved in the new version of Scout
Adding Index to Laravel Scout Conditionally (Algolia)

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