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

Attempt to read property post_id on int

I have a small response from db model, and i colud rebase it and response in route, but i see error.

My Controller:

class PostController extends Controller {
public function getLastRecord() {
    $lastRec = Post::latest('created_at')->first();

    $res = [];

    $res = collect($lastRec)->map(function($record) {
        return [
            'id' => $record->post_id,
            'rec_name' => $record->post_name,
            'user' => $record->user_id,
        ];
    })->toArray();

    return $res;
}

}

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

I want that response will be array

['id': 1, 'rec_name': 'test_name', 'user': 1]

instead names from db

['post_id': 1, 'post_name': 'test_name', 'user_id': 1]

Error:

Attempt to read property "post_id" on int

>Solution :

When you collect() a single Record, then call ->map() (or other iterative methods), it loops over your Model’s columns, not multiple columns. You can solve this by wrapping $lastRec in an array, or using ->get() instead of ->first():

$lastRec = Post::latest('created_at')->first();

return collect([$lastRec])->map(function($record) {
  return [
    'id' => $record->post_id,
    'rec_name' => $record->post_name,
    'user' => $record->user_id,
  ];
})->toArray();

// OR

$lastRecs = Post::latest('created_at')->get();

return $lastRecs->map(function ($record) {
  return [
    'id' => $record->post_id,
    'rec_name' => $record->post_name,
    'user' => $record->user_id,
  ];
})->toArray();

Or, since this is a single record (using ->first() only ever returns 1 record), you don’t need to collect() or map() at all:

$lastRec = Post::latest('created_at')->first();

return [
  'id' => $lastRec->post_id,
  'rec_name' => $lastRec->post_name,
  'user' => $lastRec->user_id
];
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