locopetey
1 month ago
225
10
Eloquent

Append new attribute based on relationships

Posted 1 month ago by locopetey

Hi,

For brevity, i have three tables with the following columns:

Categories -id -name -slug

Topics -id -name -slug -category_id

Subtopics -id -name -slug -topic_id

Calling the below get us a nicely nested JSON output..

$body = Category::with(['topic', 'topic.subtopic'])->get();

However, i want to get the absolute URL by appending it to each JSON property into Topics and Subtopics with concatenating all slugs into a new 'URL' attribute.

For example:

-URL attribute for Topics would be /category_slug/topic slug

-URL attribute for Subtopics would be /category_slug/topic slug/subtopic_slug

Thanks!

Please sign in or create an account to participate in this conversation.