Why soft deleted entities appear in query results?

Sometimes, you will get the soft deleted table entries with get() even with eloquent and protected $softDelete = true;. So to avoid this problem, use …->whereNull(‘deleted_at’)->get(); For example, this query will fetch all rows including soft deleted. DB::table(‘pages’)->select(‘id’,’title’, ‘slug’) ->where(‘is_navigation’,’=’,’yes’) ->where(‘parent_id’,’=’,$parent_id) ->orderBy(‘page_order’) ->get(); So the proper method is, DB::table(‘pages’)->select(‘id’,’title’, ‘slug’) ->where(‘is_navigation’,’=’,’yes’) ->where(‘parent_id’,’=’,$parent_id) ->whereNull(‘deleted_at’) ->orderBy(‘page_order’) ->get();

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 – Eager Loading Polymorphic Relation’s Related Models

Solution: It is possible, if you add: protected $with = [‘company’]; to both the Service and Product models. That way, the company relation is eager-loaded every time a Service or a Product is loaded, including when loaded via the polymorphic relation with History. Explanation: This will result in an additional 2 queries, one for Service … Read more

Laravel Eloquent how to get the second or third record?

$order->products()->skip(1)->first();//Second row $order->products()->skip(2)->first();//Third row …. Is more performant than loading all products and getting only first, second, ecc.. Instead if you want both second and third, you can get only them in a single query without load other rows, with similar approach: $order->products()->skip(1)->take(2)->get(); //Skip first, take second and third