1 year ago

Auto Model Binding? ? ?

Posted 1 year ago by cservices

So I have started venturing into Model Binding and really like what I can do with it. But I am seeing something that, for me anyway, seems like it is doing this binding without the need for ->with().

Example: I had some code that looked like this:

$data['this_assets_tags'] = AssetTag::where("asset_id", $id)

To access the tag data I would then do something like this in a loop:

@foreach($data['this_assets_tags'] as $tag)
                <div class="asset-view-tag-wrapper">
                    <div class="tag-name">{{ $tag->tag->tagname }}</div>

BUT, while making a few changes I ended up changing my code from above to exclude the ->with() method:

$data['this_assets_tags'] = AssetTag::where("asset_id", $id)

Lo and behold, the loop still displayed the tag name within

<div class="tag-name">{{ $tag->tag->tagname }}</div>

I cleared all caches and still it displayed the tagname.

I even did a die and dump on the variable in my class before and after it went to the view. dd($data['this_assets_tags']); and it did not have the relationship in it.

So is this the way it's supposed to work? Can we actually write a query without the with() method and still have access to the methods within the models - even chained?

I hope this makes sense. And I hope someone can explain this, cause if this is not a bug, then it's a good feature, and good to know there is automatic chaining going on. What I don't get is what is happening to memory when our models have all these relationships built into them, and all that data is being accessed whether you need it or not.

Thanks, Cy

Please sign in or create an account to participate in this conversation.