How to get model's relation by name?

23
July 12, 2018, at 02:50 AM

Is there a way to call a relation by it's name?

instead of this:

$user->comments()->create([]);

I want to use something like this:

$relation = 'comments';
$user->getRelation($relation)->create([]);

I have tried this, but I am getting :

"Undefined index: comments"
Answer 1

There are two scenarios you need to consider.

1) When you created a user and comments are not attached to it getRelation($string) returns Error: undefine index RELATION NAME 2) When you have user with comments and finding relation through getRelation($string) works like a charm.

Workaround for the problem is you need to load the relation first. Let me give you an example.

$user = new User();
$relation = 'comments';
//load method is used to load a relation.
$user->load($relation)->create(['field_name'=>"SOME VALUE"]);

Try it out and let me know whether it worked or not.

Answer 2

I think you must to be more specific. But if you wanna get the results of a relationship with eloquent you can do:

$books = App\Book::with('author')->get();

Where author, is a relationship.

Source: https://laravel.com/docs/5.6/eloquent-relationships

Answer 3

Do you mean to provide a dynamic relation name? If so you can do it like this:

$relation = 'comments';
$user->$relation->create([]);
READ ALSO
Remove the second instance of a key value pair in a collection

Remove the second instance of a key value pair in a collection

So I am trying to determine if a app is part of a list of apps that are affected by downstream servicesThe following code is what I am currently trying to do:

47
PHP replace web address test in variable

PHP replace web address test in variable

can anyone help with this? I have a web address as a variable and would like to replace multiple web address if they exist

14
Ignore optional parameter in Laravel?

Ignore optional parameter in Laravel?

Currently within my routes file I've got the following Route defined:

29