1

I am beginner in Laravel. I have this code:

$data = Term::whereDate('begin_date', '>=', $start)->whereDate('end_date',   '<=', $end)->get(['id','name','begin_date', 'end_date']);

This is work fine.

I need change my columns result: begin_date as start_date and end_date as finish_date

How can I change it?

trzew
  • 385
  • 1
  • 4
  • 13
  • Does this answer your question? [How to alias the name of a column in Eloquent](https://stackoverflow.com/questions/26958080/how-to-alias-the-name-of-a-column-in-eloquent) – Kamran Aug 06 '20 at 12:19

4 Answers4

2

You just need to pass the aliases in with the get selection

->get(['id','name','begin_date AS start_date', 'end_date AS end_date']);
aynber
  • 22,380
  • 8
  • 50
  • 63
  • Fancy. I did not know this about the ```get()``` method! – Kurt Friars Aug 06 '20 at 12:04
  • 1
    It's actually a MySQL thing. You can alias columns when you select them as `SELECT column1 AS this_column, column2 AS that_column`. The GET method just passes that along. – aynber Aug 06 '20 at 12:09
  • I am aware of the SELECT way of aliasing like in STA's answer. But I did not know get() took an argument that is essentially the SELECT. Cheers! – Kurt Friars Aug 06 '20 at 12:10
1

You can write it like this one

Term::whereDate('begin_date', '>=', $start)
   ->whereDate('end_date',   '<=', $end)
   ->get(['id','name','begin_date AS start_date', 'end_date As finish_date']);

Or by editing it in select method

Term::whereDate('begin_date', '>=', $start)
   ->whereDate('end_date',   '<=', $end)
   ->select('id','name','begin_date AS start_date', 'end_date As finish_date')
   ->get();
Joseph
  • 5,644
  • 3
  • 18
  • 44
0

Have you just tried replacing those columns in the code you pasted?

$data = Term::whereDate('start_date', '>=', $start)->whereDate('finish_date',   '<=', $end)->get(['id','name','start_date', 'finish_date']);
davidethell
  • 11,708
  • 6
  • 43
  • 63
  • Thank you. [{"title":"Testowe wydarzenie","start":"2020-07-31 08:00:00","end":"2020-07-31 09:00:00"}] - have this result. Is posible remove hour/minutes/second from result? – trzew Aug 06 '20 at 12:04
0

You can name the columns inside get method on your query. Try this:

$data = Term::whereDate('begin_date', '>=', $start)->whereDate('end_date',   '<=', $end)->get(['id','name','begin_date AS start_date', 'end_date AS finish_date']);
  • Thank you. [{"title":"Testowe wydarzenie","start":"2020-07-31 08:00:00","end":"2020-07-31 09:00:00"}] - have this result. Is posible remove hour/minutes/second from result? – trzew Aug 06 '20 at 12:09
  • Yes, possible. This way inside get: ('DATE_FORMAT(begin_date AS start_date, '%d-%M-%Y')'). Or, after fetching the result simply use like this: $data->start_date->format('d-m-Y'); –  Aug 06 '20 at 12:19