Skip to content
Advertisement

Laravel: Multilanguage details of a model

I have a model named Point having the following fields:

  • name
  • description
  • lat
  • lng

The fields “name” and “description” can be in several languages, so I created two tables for points and their details.

Schema::create('points', function (Blueprint $table) {
    $table->id();
    $table->float('lat');
    $table->float('lng');
    $table->timestamps();

Schema::create('point_details', function (Blueprint $table) {
    $table->id();
    $table->integer('point_id');
    $table->string('name');
    $table->string('description');
    $table->string('lang');

There is an index unique on point_id/language.

In the model files I have One To Many relationships

class Point extends Model
{
    public function details()
    {
        return $this->hasMany(PointDetail::class);
    }
}

class PointDetail extends Model
{
    public function point()
    {
        return $this->belongsTo(Point::class);
    }
    
}

Now I want to get the Point with details based on User language. I do so in the PointController:

class PointController extends Controller
{
    public function show($id)
    {
        $point = Point::with(['details' => function($query) {
            $query->where(
                'lang', Auth::user()->lang ? 
                Auth::user()->lang :
                'it');
            }])->find($id);
        return view('points.show',compact(['point']));
    }
}

Can I avoid the “with” clause in the Controller? Maybe making the right query in the Point model file. I’m looking for a way to return the point with one detail associated with it, based on language of the Auth::user().

Thanks for any suggestion.

Advertisement

Answer

you can add query to relationship method in point class to details method like that :

class Point extends Model
{
    public function details()
    {
        return $this->hasMany(PointDetail::class)->where('lang', Auth::user()->lang);
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement