Playing
04. For unknown models

Transcript

00:00
Another really useful use of the query method is when you don't know where a model is coming from. Now what does that mean? Well let's just say that you're building out a package or in fact you just
00:11
store a model in your config in your app someplace. Let's just call this package.php over in config and let's define out a model in here that we can chop and change. So think of something where the model might be different depending on who is using your package. So I'm going to go ahead and say model in here and I'm going to provide the full namespace to the post just
00:33
inside of here and make sure we pull that in. So with this what we can actually do is we could say config package model. Let's just die dump on that to make sure we're getting that back properly. You can see we get app models and post and ideally what we'd want to do is then start to access methods on this using Eloquent. Now what we can't do is something like this where
00:55
published true and then get. That's just not going to work. So let's just assign this to a variable die dump on posts just down here and let's come over and see what happens. There we go. Cannot call where published on a string. Of course that makes sense. We can't call methods on strings but what we can do is use the static query method to resolve this. So let's go ahead
01:19
and say query where published. So now even if you have a string within your config that dictates which model you're using in this example for a particular package you're building you can just use query on here and then start to chain on anything that you need. You can see here sure enough we get one result back like we've seen before.
7 episodes 23 mins

Overview

Ever used the Eloquent query() method in Laravel before? In this short course, we'll dive into what this method does, and demonstrate the ways it can be used.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!