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

trifek's avatar

Search in Laravel relation using json column

Hi, I have problem with search in json column.

I have 3 relations:

  • products

  • feature products

  • feature_values

My tables:

My migrations:

Product:

class Product extends Model implements Presentable
{
....
public function featureProducts()
    {
       return $this->hasMany(FeatureProduct::class, 'product_id');
        //return $this->belongsToMany(Feature::class, 'feature_product', 'id');
    }
}

FeatureProduct

class FeatureProduct extends Model
{
    protected $table = "feature_product";

    protected $with = [
        'values'
    ];

    public function values()
    {
        return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
    }

}

FeatureValues:

class FeatureValue extends Model
{
    use SoftDeletes,
        Translatable;

    protected $fillable = [
        'feature_id',
        'value'
    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $translatable = [
        'value'
    ];

    public function feature(): BelongsTo
    {
        return $this->belongsTo(Feature::class);
    }

    public function getAdminUrlAttribute(): AbstractAdminUrlPresenter
    {
        return new FeatureValueUrlPresenter($this);
    }
}

I need to show products with features and assigned features_values

I heve problem with search in json column: feature_product. feature_values_ids

When I have INT in this column, then this is working fine:

public function values()
    {
        return $this->belongsTo(FeatureValue::class, 'feature_values_ids', 'id');
    }

When I have:

["1", "2","3"]

I haven't any results :(

Haw can I repair it?

0 likes
3 replies
CorvS's avatar

@trifek Why do you store your feature_value_ids as a JSON? Create an intermediate table and use a many-to-many relationship.

public function values()
{
    return $this->belongsToMany(FeatureValue::class);
}

Assuming you have an intermediate table feature_product_feature_value with the columns feature_product_id and feature_value_id.

trifek's avatar

I know, it would be the easiest way. Unfortunately, I cannot change the tables / columns anymore. :(

CorvS's avatar
CorvS
Best Answer
Level 27

@trifek Why not? Not that hard to migrate to an actual many-to-many relationship. Would save you a lot of work in the long run.

1 like

Please or to participate in this conversation.