Laravel check if relation is empty

There are a variety of ways to do this. #1 In the query itself, you can filter models that do not have any related items: Model::has(‘posts’)->get() #2 Once you have a model, if you already have loaded the collection (which below #4 checks), you can call the count() method of the collection: $model->posts->count(); #3 If … Read more

OAuth or JWT? Which one to use and why?

JWT is a simple authentication protocol, Oauth is an authentication framework. An experienced developer will take about a month to fully understand and implement Oauth. An experienced developer can pick up the JWT protocol in about a day of reading the specifications. So basically, it boils down to your specific use-case. If you want simple … Read more

Eloquent where condition based on a “belongs to” relationship

You may try this (Check Querying Relations on Laravel website): $movies = Movie::whereHas(‘director’, function($q) { $q->where(‘name’, ‘great’); })->get(); Also if you reverse the query like: $directorsWithMovies = Director::with(‘movies’)->where(‘name’, ‘great’)->get(); // Access the movies collection $movies = $directorsWithMovies->movies; For this you need to declare a hasmany relationship in your Director model: public function movies() { return … Read more

Laravel 4 – when to use service providers?

One of the keys to building a well architected Laravel application is learning to use serviceproviders as an organizational tool. When you are registering many classes with the IoC container, all of those bindings can start to clutter your app/start files. Instead of doing container registrations in those files, create serviceproviders that register related services. … Read more