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

Mugluck's avatar

How do I apply this comparison query in Laravel?

I've been rebuilding an old php application in Laravel. Since this is effectively my first time using php it's been a pretty steep learning curve that I've been hopping up. Big thanks to all the helpful people on laracasts and the internet! Anyways, I have a chunk of code here that I can barely make heads or tails of, but not enough to convert it into a query for laravel. What I think it's doing is grabbing the Preferences collumn from one table and looking at the content in the row which looks something like this:

1A-3,1-1,1-2,3-4,4-6,4-8,6-13,6-15,8-6,8-11,7A-4,7A-5,7A-6

It looks at the items between each comma, (the tag) and checks against another table's 'tags' collumn and when there's a match it prints the result.

I think.

Can someone explain how I might print this out in laravel? Even if it's, 'Here's how you compare the two tables this way'.

print("<br><b>Preferences:</b>");
        // $mMP is transferred in the URL
        $mMP_comma = $mMP.","; // this adds a comma to the ending, needed below.
        $agency_match = "No";
                        
        $commas = substr_count ($Preferences,",");
        $comma_pos1 = 0;
        $total_items = $commas + 1;
        for ($indx = 1; $indx <= $total_items ; $indx++) {
            $lag = $comma_pos1 + 1;
            $comma_pos2 = strpos ($Preferences,",",$lag);
            $item_length = $comma_pos2 - $comma_pos1;
            $TAG = substr ($Preferences,$comma_pos1,$item_length);
            if ($indx == $total_items):
                $TAG = substr ($Preferences,$comma_pos1);
            endif;
            // echo "<br>\$indx = $indx; \$TAG = $TAG";
            $sql_pref = "SELECT subcategory,description FROM descriptor WHERE tag = '$TAG' and rank < 1000 ";
            $res_pref = mysql_query($sql_pref);
                if ($row = mysql_fetch_array($res_pref)) {
                $subcat = $row["subcategory"];
                $description = $row["description"];
                        // see if this matches the preference selection
                        // first add a comma to the tag.
                        $TAG_comma = $TAG.",";
                        // now compare to preference selection 
                        if (preg_match ("/$TAG_comma/","$mMP_comma")) {
                            print "<br><b>* $subcat - $description</b>";
                            $agency_match = "Yes";
                        }
                        else {
                            print "<br><font color='#333333'>  $subcat - $description</font>";
                        }
                }
                
            $comma_pos1 = $comma_pos2 + 1;
            
        }
0 likes
8 replies
willvincent's avatar
Level 54

The first thing I'd do is rearchitect that database.. :D

Lots of unnecessary logic in there to parse out tags, seems like it'd be quite a bit easier to just explode(',', $Preferences); then loop through each of those to find the relevant subcategory.

In the controller you could probably do something like this:

// whatever query to get $preferences, then:
$tags = explode(',', $preferences);
foreach ($tags as $tag) {
  $sub_categories[] = DB::table('descriptor')
           ->where('tag', $tag)
           ->where('rank', '<', 1000)
           ->select('subcategory', 'description')
           ->first();
}

return view('preferences', compact('sub_categories'));

in the view (preferences.blade.php):

<br><b>Preferences:</b>

@foreach ($sub_categories as $sub)
  <br><b>* {{ $sub['subcategory'] }} - {{ $sub['description'] }}</b>
@endforeach 

There's a little more going on there, but since you didn't include the whole thing it's a little tough to suss out the missing bits.

Ultimately though, at the end of the day -- this thing needs to be completely rewritten. This code is so old that trying to just do a migration to laravel is going to piss you off and waste more time than starting fresh and then running a script or two to migrate the existing awful data to a properly structured database. Doing otherwise is really an exercise in futility.

1 like
Mugluck's avatar

You have no idea how much of a pain it's been. :,D It's ok though, I'm doing exactly that, rebuilding from scratch. I didn't include the rest of the code coz it's dizzying and about 15 years old. I've actually been ignoring huge swathes of it and just figuring out what it wants to do and doing that instead. I'd redo the database, but right this moment it's still live, and I'll have to merge the live with the current database, so it's easier to deal with that once I've updated to the new system and can properly push changes through the pipeline.

Thanks you saved me a lot of trouble!

willvincent's avatar

so it's easier to deal with that once I've updated to the new system

Actually that's incorrect.. you would be better off doing it now, and writing migration scripts to move old database data (or a snapshot of it) into the new system.. then when it comes time to deploy you can just run your DB migration (laravel term) to build the new database structure, run your migration script to import/translate old data to new structure, and change where the server points.. minimal downtime, no extra time wasted reworking things.

You would be best off building it correctly now.

1 like
Mugluck's avatar

You're right. I should stop being lazy.

Though side note, your particular answer isn't sending through an array, and generates an error. Cannot use object of type stdClass as array

I've run into array/object problems before, which is normally solved by adding ->toArray() to the end, but in this case that doesn't seem possible.

To test, I'm grabbing on particular set of details:

    $min = AgencyLogin::find(196);
        $prefs = $min->Preferences;
        $tags = explode(',', $prefs);
        foreach ($tags as $tag) {
        $sub_categories[] = DB::table('descriptor')
           ->where('tag', $tag)
           ->where('rank', '<', 1000)
           ->select('subcategory', 'description')
           ->first()
        }

For whatever reason, nothing is converting to an array. I've tested a bunch of different methods and ways but we either get no data through or it just throws the error. So what am I missing?

willvincent's avatar

Which line is throwing the error? You really need to dig into your data with xdebug, or if you don't have xdebug, you can use dd() in a pinch though xdebug is better.. :)

dd($prefs);

Start with that.. I know even less about the data structure than you since I can't play with the code.

Mugluck's avatar

I made sure $prefs was printing out the correct result first to make sure it wasn't just an empty array, as there were a lot of nulls being shown in the error code.

This is Laravel 5.3 btw.

dd($prefs) gives us this: "2-5,3A-5,3A-8,5-4,5-10,5-7,5-8,7-12,8-1,8-2,8-4,8-15,8-7,8-8,8-11,8-12,8-13"-> what it should be.

The array sent to the view gets printed out according to the normal array display as you suggested:

@foreach ($sub_categories as $sub) * {{ $sub['subcategory'] }} - {{ $sub['description'] }} @endforeach

I should note that the database references are correct.

This issue lies around here: --> $sub_categories[] <-- , for a reason I don't know of, Laravel designates $sub_categories as an object of standard class and the [] doesn't convert it to an array.

I tried parsing it with object logic in the view but that didn't get me much of a result. To be honest I'm veeeery fuzzy around objects in Laravel. I know they're treated differently to arrays, but to me they're the same thing with a different name and discussions with other coders and looking into the documentation hasn't illuminated much.

willvincent's avatar

Well, objects definitely are not the same thing as arrays since objects can have methods. :)

Try explicitly defining $sub_categories as an array:

$sub_categories = [];

Then use array_push() to push items into it. That shouldn't be necessary, but try anyway.

Mugluck's avatar

Hooo boy. That's a little more complicated than I can do right this moment. I'm not even sure how to define the key, value pair defined for that. Also, I did a dd($sub_categories) to see what it was printing when I took out the [].

It only prints the first item it gets. {#262 ▼ +"subcategory": "SUPPORT ROLE" +"description": "Project Management" }

Which is interesting, but makes sense I suppose. Now to figure out how to do an array push with this query in laravel...

Please or to participate in this conversation.