Search code examples
mysqllaravellaravel-query-builder

How to make custom order and largest to smallest in laravel


My data is

id       name
----------------
1      L_one
2      z_odin
3      e_lock
4      b_block
5      L_joke

I want to make my order like this

id       name
------------------
5      L_joke
1      L_one
4      b_block
3      e_block
2      z_odin

First, I want to orderby named begin with "L". Second, I want to order id largest to smallest.
How can I code in this case?
Thank All

I had tried this problem. In real, my problem is a little complicate. So, I asked very simple solution to clear my question.




Edited

I tried code are here

Product::where('state','<>','banned')->where('created_at','LIKE',$today.'%')
    ->union(Product::orderBy('view', 'DESC'))->take(80)->get();
Product::orderBy(DB::raw('FIELD(created_at, "2021-01-18 ++")'),'DESC')->orderBy('view','desc')->get();
Product::whereDate('created_at', now())->orderBy('view','desc')->get();

I also read laravel docs. I also search similar question. But northing to solve for my problems.


Solution

  • Answer

    $answer = Model::orderByRaw('SUBSTRING(name, 1, 1)="L" desc, id desc')->get();