george572's avatar

How to reference foreignID on property ?

Sorry if this sounds dumb, I am new to Laravel.

I want to have a properties on my Product model : $table->string('from_location'); $table->string('to_location');

But the locations itself are dynamic and therefore are identified by ID's...

So, how could I make the from_location value as 2 and to_location as 1 ( for example location_id 2 = kitchen and location_id 1 = bag )

The end result I am trying to achieve in database is this $table->string('from_location') = 2 $table->string('to_location'); = 1

0 likes
3 replies
gych's avatar
gych
Best Answer
Level 29

Hey! No problem, its good that you're reaching out for help.

Create a model named Location which has a table locations where you can add the different locations like bag, kitchen, etc.

SCHEMA

For the columns in the product database schema use type integer instead of string because you want to use the id as value which is not a string but an integer(number). You could also add _id to the from_location and to_location column names to follow the conventions.

$table->integer('from_location_id');
$table->integer('to_location_id');

When you now want to add a location to a product you can use the id of that location from the locations table and set it as value in the from_location_id or to_location_id columns

RELATIONS

If this is al set, you can add relations so you can easily get the to and from locations of a product.

In the Location Model use these relations to get all the products for the from or to location.

    public function productsFrom()
    {
        return $this->hasMany(Product::class, 'from_location_id');
    }

    public function productsTo()
    {
        return $this->hasMany(Product::class, 'to_location_id');
    }

In the Product model use these relations to get the from or to location of a product.

    public function fromLocation()
    {
        return $this->belongsTo(Location::class, 'from_location_id');
    }

    public function toLocation()
    {
        return $this->belongsTo(Location::class, 'to_location_id');
    }

Also check this episode from the Laravel in 30 days serie. It explains the basics about the relations above. https://laracasts.com/series/30-days-to-learn-laravel-11/episodes/11

This are the links from the Laravel docs about these relations https://laravel.com/docs/11.x/eloquent-relationships#one-to-many https://laravel.com/docs/11.x/eloquent-relationships#one-to-many-inverse

1 like
gych's avatar

@george572 No problem :) If this solved your issue, don't forget to close your thread by selecting the best answer. If you have more questions don't hesitate to reach out

1 like

Please or to participate in this conversation.