oten
561
10
Laravel

Eloquent relationships and substring

Posted 2 years ago by oten

Hello, I'm facing a problem. Let's say we have two tables with example values.

People:

id: 1
name: John
card: DE123456

Countries:

code: DE
name: Germany

The "card" field of table "People" has a string that contains the country code and random numbers.

PeopleController.php


public function getPeople()
{
    $people = People::with('country')->get();
        return $people;
}

People.php


public function country() {
        return $this->belongsTo('App\Country', 'card', 'code');
}

Of course this returns null because the query search for 'DE123456' instead of just 'DE'. So my question is how to substring before passing the value.

Thank you.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.