Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is that possible to use IF statement to get data from database and save it into String?

I want to get some record from tbl_jadwal and save it into string in my laravel.
This is my code,

$get_time = if (now()->isMonday()) {
            return DB::table('tbl_jadwal')->where('Hari', 'Senin')->value('Jadwal_masuk');
        } else if(now()->isSaturday()) { {
            return DB::table('tbl_jadwal')->where('Hari', 'Sabtu')->value('Jadwal_masuk');
        };

$time = $get_time;

but i got message syntax error, unexpected token "if", is there any other way to solve this problem ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Broadly speaking you can do:

if (now()->isMonday()) {
    $get_time = DB::table('tbl_jadwal')->where('Hari', 'Senin')->value('Jadwal_masuk');
} else if(now()->isSaturday()) { {
    $get_time = DB::table('tbl_jadwal')->where('Hari', 'Sabtu')->value('Jadwal_masuk');
}
// Caution: $get_time may not be defined here
return $get_time??null;

You can also use when:

if (!now()->isSaturday() && !now()->isMonday()) { return null; }
    
return DB::table('tbl_jadwal')
  ->when(now()->isSaturday(), function ($q) { $q->where('Hari', 'Sabtu'); )
  ->when(now()->isMonday(), function ($q) { $q->where('Hari', 'Senin'); )
  ->value('Jadwal_masuk');

However carbon also supports localisation so you may be able to get now()->dayName to actually return the day name according to your locale.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading