1

I a have Laravel DB query like this,

$data = DB::table('jobs')
        ->select('id', 'customer_id', 'date','time')
        ->get();

I want to get the day of the date in the select query result. I'm using Carbon::parse()->isoFormat('dddd'); to get the day of the date. I want to pass the date inside of parse() & get the relevant day. I want to be the query result as, ex: 1 , 2 , Monday, 11:30 AM. How can I process that code I mentioned to get the day inside of the select query. Is it possible? Help me with a solution. I'm using Laravel 5.8. Thanks in Advance.

2
  • why are you trying to retrieve the date as day format, you can format the date field any where as a day or any other format using Carbon Commented Sep 27, 2020 at 11:53
  • by the way you can do it by defining an accessor, but I think that will suffer you in future as every time you retrieve the date it will be automatically converted to day as defined in accessor. see more about accessor here laravel.com/docs/8.x/eloquent-mutators#accessors-and-mutators Commented Sep 27, 2020 at 11:56

3 Answers 3

1

In your Job model

public function getDateAttribute($value)
{
    return Carbon::parse($value)->isoFormat('dddd');
}

Write like

$data = Job::select('id', 'customer_id', 'date','time')->get();
Sign up to request clarification or add additional context in comments.

1 Comment

I am new to laravel I'm using DB queries to do all the things. I want to retrieve the day of the date with SQL select results. how can I process the date to get output with other query results
0

Note:custome function inside select query.This is possible with model only.without model its not working.

$posts = TMCPost::select('tmc_posts.*', 'tmc_posts.id as encrypted_post_id')->get();

Inside Model

public function getEncryptedPostIdAttribute($value)
{
    return custom_function('encrypt',$value);
}

For More Brief Examples Follow Source: https://expertsuggestion.com/tutorial/laravel/how-to-use-custom-function-inside-select-query-laravel

Comments

0
$data = DB::table('jobs')
        ->select('id', 'customer_id', \DB::raw("DAYNAME(date)"),'time')
        ->get();

DAYNAME function will return the name of the day at the specific date. Here's a link!.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.