How to create a subquery using Laravel Eloquent?

This is how you do a subquery where: $q->where(‘price_date’, function($q) use ($start_date) { $q->from(‘benchmarks_table_name’) ->selectRaw(‘min(price_date)’) ->where(‘price_date’, ‘>=’, $start_date) ->where(‘ticker’, $this->ticker); }); Unfortunately orWhere requires explicitly provided $operator, otherwise it will raise an error, so in your case: $q->orWhere(‘price_date’, ‘=’, function($q) use ($start_date) { $q->from(‘benchmarks_table_name’) ->selectRaw(‘min(price_date)’) ->where(‘price_date’, ‘>=’, $start_date) ->where(‘ticker’, $this->ticker); }); EDIT: You need to … Read more

Laravel Eloquent – Attach vs Sync

attach(): Insert related models when working with many-to-many relations No array parameter is expected Example: $user = User::find(1); $user->roles()->attach(1); sync(): Similar to the attach() method, the sync() method is used to attach related models. However, the main differences are: sync() accepts an array of IDs to place on the pivot table Secondly, most important, the … Read more

How to Merge Two Eloquent Collections?

The merge method returns the merged collection, it doesn’t mutate the original collection, thus you need to do the following $original = new Collection([‘foo’]); $latest = new Collection([‘bar’]); $merged = $original->merge($latest); // Contains foo and bar. Applying the example to your code $related = new Collection(); foreach ($question->tags as $tag) { $related = $related->merge($tag->questions); }

Laravel merge relationships

Try out getter method for property which returns merged collections returned from relations. public function getCompetitionsAttribute($value) { // There two calls return collections // as defined in relations. $competitionsHome = $this->competitionsHome; $competitionsGuest = $this->competitionsGuest; // Merge collections and return single collection. return $competitionsHome->merge($competitionsGuest); } Or you can call additional methods before collection is returned to … Read more

Select Last Row in the Table

You’ll need to order by the same field you’re ordering by now, but descending. As an example, if you have a time stamp when the upload was done called upload_time, you’d do something like this; For Pre-Laravel 4 return DB::table(‘files’)->order_by(‘upload_time’, ‘desc’)->first(); For Laravel 4 and onwards return DB::table(‘files’)->orderBy(‘upload_time’, ‘desc’)->first(); For Laravel 5.7 and onwards return … Read more

Friendship system with Laravel : Many to Many relationship

tldr; you need 2 inverted relationships to make it work, check SETUP and USAGE below First off the error – this is how your relation should look like: function friends() { return $this->belongsToMany(‘User’, ‘friends’, ‘user_id’, ‘friend_id’) // if you want to rely on accepted field, then add this: ->wherePivot(‘accepted’, ‘=’, 1); } Then it will … Read more