0

So I have table called paint with data like below

id            name               allow_on
------------------------------------------
1             Avian           Wall|Roof|Wood
2             Avitex          Wall|Roof|Iron
3             Nippon          Floor|Iron
4             Some            Plastic|Cloth|other

And how to get field based on allow_on column, like "I want paint which can be used on wall" , so far my code look like this

$paints = Paint::get();
foreach($paints as $paint)
{
     $exp = explode("|", $paint->allow_on);
     foreach($exp as $pnt)
     {
         if(in_array($request->paint_name,$pnt))
         {
            var_dump($pnt)
         }
     }
}

I'm using Laravel 5.4 but i can't make it working, any solution? Thanks in advance.

6
  • What is the error? Commented Mar 7, 2017 at 13:43
  • actually, I didn't know how to query data based on request what I explained above, (I want paint whic can be used on wall), so I need suggestion how to query that data :D Commented Mar 7, 2017 at 13:49
  • 2
    Your problem stems from bad database design. Putting data in a column as a delimited list. It makes querying that data far more complex. Commented Mar 7, 2017 at 13:51
  • @RiggsFolly can you suggest the good database design?? Commented Mar 7, 2017 at 14:04
  • GOOGLE mysql database design tutorial Commented Mar 7, 2017 at 14:07

2 Answers 2

1
$want    = 'Wall';
$allowed = Paint::where('allow_on', 'like', '%'.$want.'%')->get();

foreach ($allowed as $allowedPaint) {
    echo $allowedPaint->name;
}

The above will get you all paints which can be used on wall. If you need to retrieve only the paint names, you can use:

$allowed = Paint::where('allow_on', 'like', '%'.$want.'%')->pluck('name');
var_dump($allowed);
Sign up to request clarification or add additional context in comments.

3 Comments

But i got an empty object :/
@RizalFakhri $allowed in the first case will be an eloquent collection and in the second case will be an array. Check the updated answer.
Sorry my mistake >_< Case Sensitive, Thx it's works :D
1

You are confusing the use of the needle and haystack when using in_array()

The haystack should be an array i.e. the $exp array in your example

$paints = Paint::get();
foreach($paints as $paint)
{
     $exp = explode("|", $paint->allow_on);

    if(in_array($request->paint_name,$exp)) {
            // yes paint_name is in the array
     }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.