Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

wim91's avatar

wim91 started a new conversation+100 XP

1mo ago

How to get a collection of the latest relationships with high nesting depth?

I created a category table recursively, meaning that in one table, subcategories reference the parent. This resulted in a high degree of nesting. A product belongs to a child category, and using a recursive method in the model, I retrieve all the nested relationships. I need to get a collection of the last relationship in the chain, but I'm getting "null." Could you tell me how to do this?

Here's the code.

/** class Product extends Model **/
public function category() {
      return $this->belongsTo(Category::class, 'category_id');
  }

/** class Category extends Model **/
public function parentCategories()
    {
        return $this->belongsTo(Category::class, 'category_id')->with('parentCategories');
    }
/** Controller **/

$product = Product::with('category.parentCategories')->find(2);
$parent_cat = $product->category->parent_categories;
dd($parent_cat); // null

wim91's avatar

wim91 started a new conversation+100 XP

1mo ago

How to group products by parent category with unlimited descendants?

Hello everyone. I have a category table where each parent category has an unlimited number of children. Products can only appear in the very last child category. How can I group products by parent category?

wim91's avatar

wim91 wrote a reply+100 XP

3mos ago

How can I check the uniqueness of multiple fields in one record?

Thanks for the answers. I solved the problem by creating my own rule and passing the ID of the desired record to it.

wim91's avatar

wim91 wrote a reply+100 XP

3mos ago

How can I check the uniqueness of multiple fields in one record?

Do you mean it like this?

$myId = 1;
$validated = $request->validate([
    'mydata' => 'unique:table,mydata,' . $myId. '|unique:table,mydata_2,' . $myId,
]);

It doesn't work that way for me...

wim91's avatar

wim91 started a new conversation+100 XP

3mos ago

How can I check the uniqueness of multiple fields in one record?

Hello everyone. Here's the task. Four images are added through a form. Each image has a name that is saved in the database. When updating files, I need to delete the previously saved image, upload a new one, and overwrite its name. It's possible that the new file name will match the names of three other files. My question is, how can I check the name of the uploaded file against the names of the other files, each of which is stored in the database? I found an example that only checks one field, and I have four.

$myId = 1;
$validated = $request->validate([
    'mydata' => 'unique:table,mydata,' . $myId,
]);

PS: The task requires that file names be changed, which could easily have been solved by assigning a unique name to each newly uploaded file, but alas...