Laravel 4: Eloquent relationship get all data - php

I have 2 relationship data table; users table and memberdetails table.
Users.php
class Users extends Eloquent{
public function memberdetails()
{
return $this->hasOne('Memberdetails','user_id');
}
}
Memberdetails.php
class Memberdetails extends Eloquent{
public function user()
{
return $this->belongsTo('Users','user_id');
}
}
When I try to retrieve data, with $data = User::find($id); I only get data from users table.
Example of my blade form:
{{-- User's Name, stored on user table --}}
{{ Form::text('name',null, array('id'=>'name','class'=>'form-control','required')) }}
{{-- User's address, stored on member table --}}
{{ Form::text('address',null, array('id'=>'address','class'=>'form-control','required')) }}
When I visit, localhost/user/2/edit/, the name field is populated, but address field is empty. How can I retrieve data from both tables and put into a form for editing?
Thank you.

You could use eager loading.
$user = User::with('memberdetails')->find($id);
Using this, you will automatically get the memberdetails when retrieving the user. Then you can use $user->memberdetails
Using eager loading, you do only one query to the DB so it should be the preferred way. If you dont use the with('memberdetails'), you will perform a second query when accessing the memberdetails.

After getting the user instance, access the relationship, then you can access the other class properties
$user = User::find($id);
$userData = $user->memberdetails;

Related

Laravel get record from database in blade view

I would like to known how to get data from database in blade like from User table:
{{ Auth::user()->name }}
I have table user_settings
I would like to get record from this table by logged user id like this:
{{ UserSettings::user()->my_field }}
How can I do that?
Try this on your blade view
{{ \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field }}
In default, model file is inside App folder.
Such direct access to database table is not preferred though, you can return this as a variable from controller function like,
$field = \App\UserSettings::where('user_id',Auth::user()->id)->first()->my_field;
return view('view_name',comapact('field'));
and use in blade like
{{$field}}
Another good way is posted by Orkhan in another answer using eloquent relationship.
Hope you understand.
You need to retrieve the UserSettings associated to the authenticated user:
UserSettings::where('user_id', Auth::id())->first()->my_field
You can defined a method named current() to return that for you.
class UserSettings extends Model
{
public static function current()
{
return UserSettings::where('user_id', Auth::id())->first()
}
}
Then use:
UserSettings::current()
On the other had it would better to use one-to-one relationship on user model:
class User extends Model
{
public function settings()
{
return $this->hasOne('App\UserSettings');
}
}
Then use:
Auth::user()->settings->my_field

Laravel: Trying to get property of non object

I have been writing a web application in the Laravel framework andhave come across an issue I am having with getting certain data for a user. The user structure of my web application is based on a main users table, then I have an RP table for all the users statistics such as health, energy, items they own, and so on.
When visiting a page I am trying to display this data on I am receiving the following error
Trying to get property of non-object (View: C:\workspace\mainwebsite\resources\views\frontend\home.blade.php)
O simply tried to print out the user_id column of the roleplay table for the user (and yes, I have tried other columns they output the same result)
<div class="panel panel-default">
<div class="panel-body">
{{ Auth::user()->roleplay->user_id }}
</div>
</div>
Here is my user table class:
<?php
namespace App\Database\Website\User;
use Hash;
use Eloquent;
use \Illuminate\Auth\Authenticatable;
use \Illuminate\Contracts\Auth\Authenticatable as Authentication;
class Player extends Eloquent implements Authentication
{
use Authenticatable;
protected $primaryKey = 'id';
protected $table = 'users';
public $timestamps = false;
protected $fillable = [];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
public function setUsernameAttribute($value)
{
return $this->attributes['username'] = $value;
}
public function roleplay()
{
return $this->hasOne('App\Database\Website\User\Roleplay', 'user_id');
}
}
Here is my roleplay table class:
<?php
namespace App\Database\Website\User;
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'id';
protected $table = 'srp_user_statistics';
public $timestamps = false;
protected $fillable = ['user_id'];
public function user()
{
return $this->belongsTo('App\Database\Website\User\Player', 'user_id', 'id');
}
}
Check to make sure that your current user has a roleplay object. Eloquent will return null for empty relationships.
<div class="panel panel-default">
#if(Auth::user()->roleplay)
<div class="panel-body">
{{ Auth::user()->roleplay->user_id }}
</div>
#endif
</div>
Question: why not just get the authorized user's id ({{Auth::user()->id}}) ? It appears that the roleplay object is related to the user on that id anyway; why go through a relationship to fetch an id that you already have?
Related:
Laravel Blade template how to return null instead of ErrorException when trying to get property of non-object
Probably, the authentication doesn't work in your webapp.
This is pretty basic debugging, you just need to figure out what part of that expression is not returning an object.
If the user isn't logged in, then Auth::user() would return null and since you are chaining ->roleplay after that, it would give you this error.
If Auth::user() is returning something but Auth::user()->roleplay returns null, then you would get this error because you are trying to chain ->user_id onto the end of null. The likely cause for this would be there is no roleplay data in the database for the logged in user or there is something wrong with your relationship.
By seeing your problem, it seems that you're fetching user's roleplay without actually checking that what auth()->user() is originally returning. If there isn't any authenticated user, it will return null.
You should use auth()->check() before fetching user from auth like this:
<div class="panel panel-default">
<div class="panel-body">
{{ (auth()->check()) ? auth()->user()->roleplay->user_id : '' }}
</div>
</div>
If the user is currently authenticated, then you should fetch the user details. auth()->check() returns a boolean value - false: if user isn't authenticated else it returns true
Hope this helps!

Display name of table instead of its id Laravel

I have 2 tables, tn_project has id name cv_id_project and tn_activity has id name id, i want to get the name of the project which is cv_project_name rather its id.
Basically when i click add activity i have select option to choose which project that i use, i manage to get the id of selected project but i want its name(i can select up to 3 project in a single activity)
Model
<?php namespace Activity;
use Illuminate\Database\Eloquent\Model;
class Activity extends Model {
protected $table = 'tn_activity';
public $timestamps = false;
public function projectModel(){
return $this->hasMany('Activity\Project','cv_id_project','id');
}
}
VIEW
#foreach($query as $result)
<td>{{$result->projectModel->cv_project_name}}</td>
#endforeach
Controller
public function index(){
return view('landing-page')
->with('title','Landing Page')
->with('query',Activity::with('projectModel')->get())
->with('projects',Project::all());
}
usually it's work but i don't know what makes it error
and then this error occured
Undefined property: Illuminate\Database\Eloquent\Collection::$cv_project_name (View: C:\xampp\htdocs\PKL\netxcel-2-backup2\resources\views\landing-page.blade.php)
Your Activity projectModel is a collection, because it has hasMany relationship. If it's really true, you should get the project name like this.
#foreach ($result->projectModel as $project)
<td>{{$project->cv_project_name}}</td>
#endforeach
However, if it shouldn't have hasMany relationship than you should change the hasMany part

Laravel many to many retrieve data across multi table

Database Table Relationship
What I did:
public function index(Request $request)
{
$company_feedback = $request->user()->company()
->get()->pluck('id')- >toArray();
$company = Company::whereIn('id',$company_feedback);
$feedback = $company->feedback;
return view('feedback.index', ['feedbacks' => $feedback]);
}
By using eloquent relationship, how to retrieve feedback data from a specific user id ? I want show feedback data which belong to current login user login id.
anyone could help? show me how to write the code in Index method in Feedback class.
Assuming you have two models User.php and Feedback.php
If you want to retrieve all feedback given by a current user
In your User.php
public function feedback()
{
//assuming you have user_id column in feedback table
return $this->hasMany("App\Feedback",'user_id');
}
In your controller
//all feedback given by the current user
$feedbacks = Auth::user()->feedback;

Laravel - Updating OneToOne relationship

I have two models 'User' and 'Profile'.
'email' field is in User model whereas 'name' field is in Profile model.
'profiles' table has a foreign key of 'user_id'.
I searched a lot but couldn't find a proper solution on how I can update both of these entities in one go.
In my ProfileController, I am doing this but I am sure there is a better way. Please help.
public function update($id)
{
$profile = Profile::where('id', $id);
$profile->name = 'Jon';
$profile->save();
$user = User::where('id', $profile->user_id);
$user->email = 'newjon#example.com';
$user->save();
}
My Profile model has
public function user()
{
return $this->belongsTo('User');
}
And my User model has
public function profile()
{
return $this->hasOne('Profile');
}
You can't do it in one go.
However you could simplify it a bit, by leveraging Laravel features, like this (and do it in one-go-like way):
1 Controller edit
$profile = Profile::with('user')->find($id);
// make sure you eager load the user for below to work
2 View
{{ Form::model($profile) }}
{{ Form::text('name') }}
{{ Form::text('user[email]') }}
{{ Form::close() }}
this will autopopulate your profile data (and user data too)
3 Controller update
$profile = Profile::find($id);
$profile->fill(Input::only(.. fields you want to update ..));
$profile->user->fill(Input::get('user')); // array of user data form the form
$profile->push(); // save both models in one go BUT separate queries
Also make sure you have fillable on your models, so fill will does its job.
Another way would be using model events, but I wouldn't do it that way.

Categories