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 ))
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 }}
Since your pivot table has extra column text, you need to define the column name while defining the relationship
According to Official Doc
By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:
public function features(){
return $this->belongsToMany('App\Feature')->withPivot('text');
}
And for Retrieving the intermediate table column, you need to use the pivot attribute.
Language Model
<?php // Languages Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Language extends Model
{
public function features(){
return $this->belongsToMany('App\Feature', 'feature_language', 'feature_id', 'language_id')->withPivot('text');
}
public function getDefaulLanguage(){
return $this->default_back;
}
public function featureTranslation($code){
return $this->features()->where('code', $code)->first()->pivot->text;
}
}
?>
Index View
<?php
<h1>login : {{ $language_default->featureTranslation("login") }}</h1>
?>
Related
"data":
"{\"thread\":{\"user_id\":76,\"parent_id\":\"139\",\"item_id\":\"178\",\"comment\":\"s\",\"updated_at\":\"2017-09-18
15:19:24\",\"created_at\":\"2017-09-18
15:19:24\",\"id\":140},\"user\":{\"id\":76,\"name\":\"Kavi\",\"lastname\":\"Arasan\",\"mobile\":\"822-034-1179\",\"email\":\"kayalmanimohana#gmail.com\",\"verified\":0,\"email_token\":\"1ATrlUoyWy\",\"created_at\":\"2017-09-15
16:47:59\",\"updated_at\":\"2017-09-18
15:18:57\",\"address\":null,\"city\":null,\"state\":null,\"country\":null,\"pin\":null,\"profile\":null,\"gender\":null,\"street_num\":null,\"provider\":null,\"provider_id\":null,\"is_delete\":null,\"username\":\"dummy\"}}",
i have data object like this in my db. How do i get the user id present within thread of data? Am using laravel
#kayal if you are still learning then this is good but sometime you should read the documentation
here is the method that you can do this easily
For Example
Assuming Table name test
+------------+
| id | data |
+------------+
| 1 | {...} |
+------------+
suppose you have Model Test.php
Then add a protected property $casts it is an array in this array add key => value key is column name and value will be in which type you want to cast like object or array in this case i am using object.
namespace App;
class Test extends Model
{
protected $casts = ['data' => 'object']; // add this property
in your controller
in this case i am using TestController.php
namespace App\Http\Controllers;
use App\Test;
class TestController extends Controller
{
public function seeUserId()
{
$test = Test::find(1); // or your query
$user_id = $test->data->thread->user_id; // you can access like this this is only example
}
public function saveData($data)
{
$test = new Test;
$test->data = $data; // don't use json_encode() just pass any object or array ;
$test->save();
}
laravel doc :- https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting
foreach ($unread as $unr) {
$data = json_decode($unr->data,true);
$user_id = $data['thread']['user_id'];
}
This made it possible
i need help for make something : I have 2 table :
- Users
----------
id_user
- Sports
----------
id_sport
title_sport
User can practice 1 or more sport.
User can search user who practice 1 or more sport.
Can you help me please for the model User?
Can i use something like this ?
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function pratice()
{
return $this->belongsToMany('App\Sport');
}
public function search_user()
{
return $this->belongsToMany('App\Sport');
}
}
with 2 pivots table.
Hi im new to laravel and not much of a programmer so I have this code inside my controller that i wanted to get the result set that is based from database records then use it as a selection for a dropdown on my view here is my code inside my controller
$rcrdID = DB::table('dbo_studentrecord')
->join('dbo_students','dbo_studentrecord.StudentID' ,'=' ,'dbo_students.StudentID')
->lists(DB::raw('CONCAT("ID ", dbo_studentrecord.StudentID, " | " ,dbo_students.FirstName, " ", dbo_students.LastName)'),'StudentRecordID');
im trying to make the dropdown look like for example:
ID | 1 | Billy | Joe | 12345
is there a better way to do this? thanks much
You should make relation between the Student and StudentRecord model.
Student model (App\Student.php):
class Student extends Model {
protected $table = 'students';
public function StudentRecord() {
return $this->hasOne('App\StudentRecord');
}
}
StudentRecord model (App\StudentRecord.php):
class StudentRecord extends Model {
protected $table = 'student_records';
public function Student() {
return $this->belongsTo('App\Student');
}
}
If you created the relation (one-to-one) you can use the below query in the Controller:
namespace App\Http\Controllers;
use Student;
use StudentRecord;
class StudentController extends Controller {
public function getStudent($id) {
return Student::find($id)->load('StudentRecord');
}
}
You can read about the load() function.
The Setup And Dummy Data
I have a simple model called Category, which has the following schema:
|----------------------------------------------|
| cat_id | cat_name | parent_id |
|----------------------------------------------|
| 1 | Home | 0 |
|----------------------------------------------|
| 2 | Products | 1 |
|----------------------------------------------|
| 3 | Services | 1 |
|----------------------------------------------|
| 4 | Product A | 2 |
|----------------------------------------------|
| 5 | Product B | 2 |
|----------------------------------------------|
The Desired Output
So you can see that we would get a very straight forward hierarchy as follows:
Home
- Products
- Product A
- Product B
- Services
The Issue
I'm trying to map this relationship in Laravel 4.2, so that I can query a model and get its parent (it will always have a parent), and child categories if they exist.
I've defined the relationship in the Category model using:
public function children()
{
return $this->hasMany('Category', 'parent_id', 'cat_id');
}
public function parent()
{
return $this->belongsTo('Category', 'parent_id');
}
The Problem
I can get the parent name working, using
$category = Category::findOrFail($id);
return $category->parent->cat_name;
However, I don't understand how to get the child objects.
I've tried:
$category = Category::findOrFail($id);
$children = $category->children();
But when I dd($children) it doesn't output what I'd expect.
Calling the relationship function (->children()) will return an instance of the relation class. You either need to call then get() or just use the property:
$children = $category->children()->get();
// or
$children = $category->children;
Further explanation
Actually children() and children are something pretty different. children() just calls the method you defined for your relationship. The method returns an object of HasMany. You can use this to apply further query methods. For example:
$category->children()->orderBy('firstname')->get();
Now accessing the property children works differently. You never defined it, so Laravel does some magic in the background.
Let's have a look at Illuminate\Database\Eloquent\Model:
public function __get($key)
{
return $this->getAttribute($key);
}
The __get function is called when you try to access a property on a PHP object that doesn't actually exist.
public function getAttribute($key)
{
$inAttributes = array_key_exists($key, $this->attributes);
// If the key references an attribute, we can just go ahead and return the
// plain attribute value from the model. This allows every attribute to
// be dynamically accessed through the _get method without accessors.
if ($inAttributes || $this->hasGetMutator($key))
{
return $this->getAttributeValue($key);
}
// If the key already exists in the relationships array, it just means the
// relationship has already been loaded, so we'll just return it out of
// here because there is no need to query within the relations twice.
if (array_key_exists($key, $this->relations))
{
return $this->relations[$key];
}
// If the "attribute" exists as a method on the model, we will just assume
// it is a relationship and will load and return results from the query
// and hydrate the relationship's value on the "relationships" array.
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
}
Then in getAttribute first is some code that checks for "normal" attributes and returns then. And finally, at the end of the method, if there's a relation method defined getRelationshipFromMethod is called.
It will then retrieve the result of the relationship and return that.
Set this in model and try :
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
public function grandchildren()
{
return $this->children()->with('grandchildren');
}
table MemberOwner:
id | name | time
table Member:
id | sex | age
talbe MemberOwner_Member:
id | ownerid | memberid
and this is my relationship-defined code:
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','?','?');
}
}
look at the question mark above,how to fill with it?thank you,I've tried
ownerid,memberid
and
memberid,ownerid
but neither of them works,I need you help ,thanks again!
Try this:
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','foreign key','localkey');
}
}
Here we are specifying this in MemberOwner model and for MemberOwner_Member table foreign key would be ownerid and if you want to specify local id then it would be id which is primary key there.
Use this:
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','ownerid');
}
}
And this will work also if you want to specify local key.
class MemberOwner extends Eloquent {
public function members()
{
return $this->belongsToMany('Member','MemberOwner_Member','ownerid','id');
}
}