Answer the question
In order to leave comments, you need to log in
How to use a string in Laravel as a relationship/field argument from a database table?
Good day!
There is a $product object, which has such fields as 'scu', 'price' and others in the database. There is an array with some of these fields $titles = ['scu', 'price', 'product', 'slug', ...];
Is it possible to somehow get the value of these fields from the database for a specific product by substituting the values of the specified array, as if I were doing $product->scu? That is, of type $product->$titles[0]. Such a complexity, because, depending on complex conditions, you need to get only certain data for the product, and it would be great to implement the extraction of the necessary data by substituting an array element into the relation. It can be done through a switch case, but this option was left as a spare.
Thank you! I hope I explained the crutch clearly)
Answer the question
In order to leave comments, you need to log in
You have already been answered above, but you are talking about relationships, maybe you get a product through relationships, then let's say you have a Category model that has Relation products
$category->products()->select($titles)->get()
- pay attention to () after products - this is important because we are calling the function
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question