PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 15, 2022

[FIXED] How to make custom orderBy or DB::raw(FIELD()) with LIKE keyword and passing variable in laravel query builder

 November 15, 2022     laravel, laravel-6, laravel-query-builder, mysql     No comments   

Issue

I have a very simple solution but I dislike that. So, How can I do?

my data base is

--------------------------------------
id   name   view       created_at
--------------------------------------
1   one     9      2021-01-13 12:34:22
2   two     8      2021-01-15 10:23:02
3   three   23     2021-01-15 20:55:17
4   forth   15     2021-01-16 12:34:22
5   fifth   0      2021-01-19 10:37:02

I want to sort and get my data like this--

--------------------------------------
id   name   view       created_at
--------------------------------------
5   fifth   0      2021-01-19 10:37:02
3   three   23     2021-01-15 20:55:17
4   forth   15     2021-01-16 12:34:22
1   one     9     2021-01-13 12:34:22
2   two     8     2021-01-15 10:23:02

My solution is

        $today = '2021-01-19';  //this date will calculate in daily. Not absolute date!

        $firstarray=Product::where('created_at','LIKE',$today.'%')->get();
        $secondarray=Product::orderBy('viewer', 'DESC')->get();
        $data = array_merge($firstarray,$secondarray);
        return $data;

In real, I want to make my code like this

    $today = '2021-01-19';  //this date will calculate in daily. Not absolute date!
    $data = Product::orderBy(DB::raw('FIELD(created_at, LIKE $today."%")'),'DESC')
            ->orderBy('view','desc')->get();
    return $data;

How can I get powerful code for my problem?

Sorry for my english skill
thank all


Solution

Your question is not clear! If it's the way I understand, that's the solution.

$data = Product::whereDate('created_at', now())->orderBy('view','desc')->get();


Answered By - Yunus Kocabay
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing