Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laracasts9924's avatar

rearrange datafields in json response

So we are using Lumen for APIs. We are using SQL server which we cannot tell Laravel in migrations to place new columns exactly where we want them. So over the year we have added columns which get added to the end of the SQL table. So does anyone know a way to arrange/rearrange NOT based on the current table order but how we want to send them back in the response. For example, we have 3 columns in our table at different locations: (daily_charge, monthly_charge, yearly_charge). I want to send them back in the json response together one after the other.

Thanks!

0 likes
7 replies
jlrdw's avatar

Have you tried SSMS? Just suggestion.

Edit: But returned data should be in same order as the query columns:

SELECT a,c,b ...

instead of

SELECT a,b,c ...

Should give order of columns you want.

laracasts9924's avatar

@jlrdw thanks for the response. Yes, you are correct you can arrange columns as you want using SSMS. Our problem is we are not written individual SQL statements for each API endpoint but are using Laravel Eloquent relationships and Eloquent builder so the columns come back as is in the response. So I am wondering if anyone has came across this issue before and it they found a possible solution or did not find a possible solution?

Thanks!

jlrdw's avatar

You should be able to order fields in eloquent as well. What does query look like. If you can't use a regular query, but suggestion only. Eloquent converts to regular sql at runtime.

laracasts9924's avatar

@jlrdw sure, pretty simple.

$query = Post::newQuery();

which of course returns a toSql() statement of

select * from [posts]

so where Post is in the above statement, it can actually be whatever model we are passing in.

Thanks again!

apex1's avatar

Pretty sure JSON cannot and will not guarantee order of keys.

jlrdw's avatar
jlrdw
Best Answer
Level 75

@dxladner i meant like this example:

        $dogid = Request::input('somevar');
        //$dog = Dog::where('dogid', $dogid)->first();
        $dog = Dog::select('dogname', 'comments', 'lastedit', 'dogid')
                ->where('dogid', '<', $dogid)
                ->get();

        return Response::json($dog);

Raw output in network tab

[{"dogname":"Belle","comments":"Yr old female. I was found at a rest stop, some tourist brought me here.","lastedit":"2015-03-11 10:18:07","dogid":1},{"dogname":"Dale Evans","comments":"4 month female lab mix. Curious playful puppy.","lastedit":"2015-01-28 09:44:06","dogid":2}]

Notice dogid is last in the json, but in actual database it is first, you can "select" in the order you need.

Just test data I use..

Please or to participate in this conversation.