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
Related
I have two table as sbj_topics and difficulty_level_sbj_topic so, I want to define relationship b\w them to fetch records, so to make relationship I have done this,
SbjTopic.php:
public function difficulty_level_sbj_topic() {
return $this->hasMany('App\DiffiLvlSbjTopic');
}
And in DiffiLvlSbjTopic.php:
protected $table = 'difficulty_level_sbj_topic';
public function sbj_topics() {
return $this->belongsTo('App\SbjTopic');
}
After that I returned the data to a view as:
$easy = DiffiLvlSbjTopic::where(['subject_id' => $id, 'difficulty_level_id' => 2])->get();
return view('diffi_lvls.show', compact('easy'));
Then in the view I done this:
#foreach($easy as $easy)
{{ $easy->sbj_topics }}
#endforeach
but the page is blank, and when I do this {{ $easy->sbj_topics->sbj_topic_name }} trying to get property of undefined! comes.
The main purpose of creating relationship is to display Subject Topic Name because I have foreign key as sbj_topic_id in difficulty_level_sbj_topic table so if anyone has any other idea to do this without relationship that will be awesome.
Break this down:
SbjTopic - has many difflevels
a difflevel belongs to aSbjTopic
With this understanding, I can see you are getting the difflevels (DiffiLvlSbjTopic). This is actually what you are passing to your blade.
So first off: complete your relationship by specify the foreign keys. i.e:
In the SbjTopics model:
public function difficulty_level_sbj_topic() {
return $this->hasMany('App\DiffiLvlSbjTopic', 'subject_id');
}
with this, you know that in the 'difficulty_level_sbj_topic' you must have the column subject_id.
Now define the reverse relationship in your DiffiLvlSbjTopic model:
public function sbj_topics() {
return $this->belongsTo('App\SbjTopic', 'subject_id');
}
With all these in place in your controller or route all you need to do is fetch the DiffiLvlSbjTopic model properties. For instance:
public function index () {
$easy = DiffiLvlSbjTopic::all();
return view('diffi_lvls.show', compact('easy'));
}
Finally in your view:
#foreach($easy as $difflevel)
<div>{{ $difflevel->sbj_topics->name }} </div>
#endforeach
That's it.
Your both variables should not be $easy it can be something like $easy as $easySingle. And add a loop inside like
#foreach($easy as $easySingle)
foreach ($easySingle->sbj_topics as $topic) {
$topic->property;
}
#endforeach
I'm using Laravel 5.2. In my application, if a user is an admin, he can see all groups. Otherwise, he can only see his groups.
Model
public function groups() {
if ($this->isAdmin()) {
return \App\Group::get();
}
return $this->belongsToMany('App\Group');
}
View
#foreach($user->groups as $group)
{{ $group->name }}
#endforeach
Result
The code above works if the user is not an admin, but I get this error if the user is an admin
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation
I tried this instead: $user->groups() as $group, it works when the user is an admin, but show nothing when it's not an admin.
Question
I know when I call a relation as a property ($user->groups), it returns a collection of objects. Instead, if I call it as a function ($user->groups()), I get a QueryBuilder instance.
What can I do to use the same syntax as in my view ?
Note: I cannot add all groups in the database to the admin, as admins must have no group.
The way is not using directly relationship for this but using extra method to handle this.
First in your model create simple relationship:
public function groups()
{
return $this->belongsToMany('App\Group');
}
and then create extra method:
public function availableGroups()
{
if ($this->isAdmin()) {
return \App\Group::get();
}
return $this->groups;
}
Now in view you can use:
#foreach($user->availableGroups() as $group)
{{ $group->name }}
#endforeach
I am new to Laravel 5 and was wondering how model object retrieval works.
For instance I have a separate table that is referenced by another table and I want to get the records from that.
Item Table
Category Table
I was trying to extend the User model
Class Item extends Model {
public function getCategory(){
$category = Category::find($this->category_id);
return $category;
}
}
So when I try to access the object retrieved in my view,
{{ $item->getCategory()->name }}
I get the error
Undefined property: Illuminate\Database\Eloquent\Builder::$name
What am I doing wrong? And what is the best practice in doing this? I used to do this in Symfony and it works so I was wondering how its done in Laravel.
Any help and input would be greatly appreciated.
Thank you all.
As stated in the docs here's how I did it
Class Item extends Model {
public function category()
{
return $this->hasOne('App\Category', 'id', 'category_id');
}
}
And accessed the object in the view this way
{{ $item->category->name }}
I have a dynamic property user in my model:
class Training extends Model
{
...
public function user()
{
return $this->belongsTo('App\User');
}
}
And I can easy get username in controller like this:
Training::find(1)->user->name
But I don't know how to perform the same in view. I tried this:
Controller:
return view('training/single', Training::find(1));
View:
{{ $user->name }};
but without success, I'm getting error Undefined variable: user. So it's look like I can't access dynamic property in view.
Any idea how can I use dynamic property in views?
I fear that's not really possible. There's no way to set the $this context in your view to the model. You could convert the model into an array with toArray() but that would include the related model and you would have to access it with $user['name'].
I personally would just declare the user variable explicitly:
$training = Training::find(1);
return view('training/single', ['training' => $training, 'user' => $training->user]);
Use eager loading
return view('training/single', Training::with('user')->find(1));
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;