Adam Ibrahim Adam Ibrahim - 3 months ago 19
PHP Question

Laravel 5 pivot tables are not working

I am trying to change the home page text languages from database using Pivot tables relationship.
All works fine and I am getting no errors but the word login is not shown.
I have 3 tables

languages

id | name | sign | default_back
1 | English | en | 1
2 | Russian | ru | 0


features

id | code | type
70 | login | 0


feature_language

id | feature_id | language_id | text
1 | 70 | 2 | Ru Login
2 | 70 | 1 | Login


Language Model

<?php // Languages Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Language extends Model
{
public function features(){
return $this->belongsToMany('App\Feature');
}
public function getDefaulLanguage(){
return $this->default_back;
}
public function featureTranslation($code){
return $this->features()->where('code', '=', $code)->first();
}
}
?>


Features Model

<?php // Features Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Feature extends Model
{
}
?>


Index controller

<?php // index controller
namespace App\Http\Controllers
use App\Language;
class HomeController extends Controller {

public function index(){
$languages = Language::get();
$language_default = Language::where('default_back', '>', '0')->first();

return view('index')->with('languages', $languages)
->with('language_default', $language_default);
}
}
?>


Index View

<?php
<h1>login : {{ $language_default->featureTranslation("login")->text}}</h1>
?>


Any help will be appreciated ))

Answer

First, you need to define your pivot table column name in your model.

Language Model:

public function features()
{
    return $this->belongsToMany('App\Feature')->withPivot('text');
}

In you Index View, you need to access data like following:

{{ $language_default->featureTranslation("login")->pivot->text }}
Comments