Home > database >  Attempt to read property post_id on int
Attempt to read property post_id on int

Time:09-08

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;
}

}

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

CodePudding user response:

When you collect() a single Record, then call ->map() (or other iterative methods), it loops over your Model's columns, not multiple Post records. 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
];
  • Related