I have two models Product
and ImageCat
with a many-to-many relationship and in the pivot table I also store the absolute path of the image so that this is an example of what the pivot table can have
+------------+-------------+---------------------- -----------------------+ | product_id | imagecat_id | filepath | +------------+-------------+---------------------- -----------------------+ | 1 | 1 | /home/takyo/www/laravel/public/img/img1.jpg | | 1 | 2 | /home/takyo/www/laravel/public/img/img2.jpg | | 2 | 1 | /home/takyo/www/laravel/public/img/img3.jpg | +------------+----------+------------------------- --------------------+
to access the path of the image and put it in the src of a label, <img>
it is not worth directly accessing the filepath
{{ $product->images->find(1)->pivot->filepath }}
What I don't know is if with eloquent you can directly access a parser that I have programmed somewhere so that I can do this like that.
Note: src is the filepath parser
{{ $product->images->find(1)->src }}
or so
{{ $product->images->find(1)->pivot->src }}
I already know that the quick solution is to create another src attribute or that the route is directly the public one of the server. This question is for a doubt in my learning.
Another example that occurs to me could be
$user->nombre_completo
where the full_name attribute is not in the database and it is the union of the first and last name fields
You can use an Accessor to return new calculated values of existing attributes in a model:
As you can see, the value that this function will return will be the concatenation of the attributes
nombre
andapellido
, which do have a corresponding column in the DB. Then, to access the value of the Accessor, you can access the attributenombre_completo
on a model instance:This will serve you well while you are working directly on an Eloquent\Model instance. If you also want these computed values to be added to your model's array/JSON representations, you'll need to append them.
Appending Values to a Model's Array/JSON
Occasionally, when converting models to an array or JSON, you may want to add attributes that don't have a corresponding column in your database. After creating the accessor (I'm sticking with the full name example), add the attribute name to the property
appends
in the model. Note that attribute names are usually mentioned in "snake_case", even though the accessor is defined using "camelCase":Once the attribute has been added to the attachment list, it will be included in both the model array and the JSON representations.
Alternatively, you can cast a model or collection to a
string
, which will automatically call the methodtoJson
on the model or collection:Since models and collections are converted to JSON when converted to a string, if you return Eloquent objects directly from your application's routes or controllers, they will also contain the appended attributes: