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

eggplantSword's avatar

Find item that has different names but refer to the same item

I'm trying to do an import of a school's courses and their teacher and students, the thing is these are auto generated reports and sometimes a course will have more than one name depending on the course plan, for example a general english 1 class can have a different name if you're studying engineering or nursing, could be english 1 and basic english 1.

This is the small method I'm using to get the relevant course

private function getCourse($name, $num)
    {
        $course = Course::where('name', $name)->where('num', $num)->first();
        if (empty($course)) {
            $course = new Course();
        }
        return $course;
    }

How can I in the best way check for these different names? Should I put them in an array or what's my best choice?

0 likes
5 replies
bobbybouwmann's avatar

Yeah, an array seems to be the best option here. You can use the method whereIn to make this work

Course::whereIn('name', ['englsh 1', 'basic english 1'])->first();

Well, you get the idea ;)

2 likes
eggplantSword's avatar

@snapey Not all courses have alternate names and these names would only be used in that one method I posted above, putting that in the database instead of just making an array in the method seems unnecessary to me.

1 like
eggplantSword's avatar

@bobbybouwmann How can I do that more dynamically? Right now I have around 16 courses but there are going to be a lot more how can I do this without a lot of if-elses? I had thought of something like this but if there end up being 50 or more courses with multiple names this method would be super long.

if ($name === 'Inglés I') {
    $name = 'Inglés Básico I';
} 

$course = Course::where('name', $name)->where('num', $num)->first();
if (empty($course)) {
    $course = new Course();
}
return $course;
bobbybouwmann's avatar

Well, you have a few options here. The basic idea is the same though. You need to have a central place where you can map the name to a generic name. This can be a database or a config file as an example. Once you have a lookup structure like that, you can write one method that always gives back to the correct string for you, no matter what you feed it.

Here is a database example

$courseName = CourseNames::where('name', 'Inglés I')->first();
$courseName = CourseName::find(($courseName->parent_id);

$course = Course::where('name', $courseName->name)->where('num', $num)->first();

Another solution is using a one-to-many relationship. between course and coursename. This way, you can make it even simpler

As you can see, lot's of options here.

Please or to participate in this conversation.