G
G
GaserV2017-05-15 23:55:14
Laravel
GaserV, 2017-05-15 23:55:14

How to return an array of IDs in Laravel?

Tell me please. How can I return an array of IDs in the model? I have a Ticket model. It has a link to messages:

public function messages()
  {
    return $this->hasMany('App\Message');
  }

For the API, I have added the messagesIds method which should return an array of IDs.. How can I do this? Heard that ORM should return an object, but I need an array.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Stanislav Pochepko, 2017-05-16
@DJZT

$message->tikets->lists('id')->toArray()
It was like that, as far as I remember.

M
Mokhirjon Naimov, 2017-05-16
@zvermafia

Try like this:

public function messagesIds()
{
    $this->messages->pluck('id')->toArray();
}

C
chelkaz, 2017-05-16
@chelkaz

It is necessary to specify the with("messages") method when calling the model.
But the array count:
In the model itself, you can specify:

protected $casts = [
        'options' => 'array',
    ];

Details https://laravel.com/docs/5.4/eloquent-mutators#arr...

H
hopeful_romantic, 2017-05-16
@hopeful_romantic

return $this->hasMany('App\Message')->select(['id', 'message_id']);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question