Your Location is: Home > Php

Laravel orderBy and COALESCE together issue in PHP

From: United View: 4394 Andrea Giannoni 


I have a problem with a function in Laravel: I have a table that has to return me all the elements ordered by the creation data (created_at). Then I need the possibility to put an specific element in a declared position.

Element 1 = 12.01.2012
Element 2 = 11.01.2009
Element 3 = 19.05.2005
Element 4 = 23.04.2001

Element 1
Element 2
Element 3
Element 4

if i put the Element 4 in second position position i want the result:

Element 1
Element 4
Element 2
Element 3

I tried with COALESCE and this is my code:

public function playlist()
  $playlist = Playlist::orderBy(\DB::raw("COALESCE('null', 'ordinamento')", "ASC", "created_at", "DESC"))

  return view('pages.playlist', compact("playlist"));


Best answer