Laravel 5.3 Eloquent Relationships

i’m using Laravel 5.3

and i’m trying to select from the database the values for the lang files,

i created a file and named it global.php

and inside the file i tried to do this:

use AppDictionary;

$language_id = 1;

$dictionary = array();
$lables     = Dictionary::where('language_id',$language_id)->get();
foreach($lables as $label):
    $dictionary[$label->label] = $label->value;
endforeach;

return $dictionary;

now, this is working but i want to select the rows using the short_name field and not the id of the language

i want it to be something like this:

$lables     = Dictionary::all()->language()->where('short_name', 'en')->get();

my database looks like this:

Languages

id
name // for example: English
short_name // for exmaple: en

Dictionary
id
key
value
language_id

and my models looks like this:

Language Model

namespace App;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class Language extends Model
{
    use SoftDeletes;
    protected $softDelete = true;
    protected $dates = ['deleted_at'];

    public function dictionary()
    {
        return $this->hasMany('AppDictionary');
    }
}

Dictionary Model
<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class Dictionary extends Model
{
    protected $table = 'dictionary';

    public function language()
    {
        return $this->belongsTo('AppLanguage');
    }

}

thank you for your help!

!!!UPDATE!!!

i added 1 more table called

Labels

id
label_name

and change the dictionary table to:

Dictionary

id
lable_id
value
language_id

how can i make this work so i can pull the label_name instead of the label_id
$lables = Dictionary::whereHas('language', function($query) {
    $short_name = basename(__DIR__);
    $query->where('short_name', $short_name);
})->pluck('value', 'label_id')->toArray();

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use Laravel’s whereHas() function as:

$lables = Dictionary::whereHas('language', function($query) {
    $query->where('short_name', 'en');
})->get();

Update

If you want to get rid of your foreach() then you can use Laravel’s pluck() function as:

$lables = Dictionary::whereHas('language', function($query) {
    $query->where('short_name', 'en');
})->pluck('value', 'label')->toArray();

Method 2

I guess it could be something like:

$lables     = Dictionary::with('language')->where('short_name', 'en')->get();


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x