Get array of Eloquent model's relations

eloquent, laravel, php

Solution

It's not possible because relationships are loaded only when requested either by using `with` (for eager loading) or using relationship public method defined in the model, for example, if a `Author` model is created with following relationship

public function articles() {
    return $this->hasMany('Article');
}

When you call this method like:

$author = Author::find(1);
$author->articles; // <-- this will load related article models as a collection

Also, as I said `with`, when you use something like this:

$article = Article::with('author')->get(1);

In this case, the first article (with id 1) will be loaded with it's related model `Author` and you can use

$article->author->name; // to access the name field from related/loaded author model

So, it's not possible to get the relations magically without using appropriate method for loading of relationships but once you load the relationship (related models) then you may use something like this to get the relations:

$article = Article::with(['category', 'author'])->first();
$article->getRelations(); // get all the related models
$article->getRelation('author'); // to get only related author model

To convert them to an `array` you may use `toArray()` method like:

dd($article->getRelations()->toArray()); // dump and die as array

The `relationsToArray()` method works on a model which is loaded with it's related models. This method converts related models to array form where `toArray()` method converts all the data of a model (with relationship) to array, here is the source code:

public function toArray()
{
     $attributes = $this->attributesToArray();

     return array_merge($attributes, $this->relationsToArray());
}

It merges model attributes and it's related model's attributes after converting to array then returns it.

Problem

I'm trying to get an array of all of my model's associations. I have the following model: ``` class Article extends Eloquent { protected $guarded = array(); public static $rules = array(); public function author() { return $this->belongsTo('Author'); } public function category() { return $this->belongsTo('Category'); } } ``` From this model, I'm trying to get the following array of its relations: ``` array( 'author', 'category' ) ``` I'm looking for a way to pull this array out from the model automatically. I've found this definition of a relationsToArray method on an Eloquent model, which appears to return an array of the model's relations. It seems to use the $this->relations attribute of the Eloquent model. However, this method returns an empty array, and the relations attribute is an empty array, despite having my relations set up correctly. What is $this->relations used for if not to store model relations? Is there any way that I can get an array of my model's relations automatically?

Original source

Related problems