laravel Eloquent: Relationships get third part relation - php

iam working in journal project and i have 3 main table related
Volumes->issues->articles
volume has many issue but issue has one volume
issues has many articles but article has one issue
all working fine but i have 1 tricky step
i want to get volume name when view all articles. i want view the following when retrieving articles
article name | vol name/issue name
i success to get issue name as i have relation between article module and issue module but i dont know how to get volume name inside for-each articles
<tr>
<th>Title</th>
<th>Vol/Issue</th>
</tr>
#foreach($articles as $article)
<td>{{ $article->title }}
<td>{{ ??? }} / {{$article->issue->name}}</td>
#endforeach

Assuming you have the belongs to relations set up in each model to act as the reverse of your has many relations:
class Article extends Model
{
public function issue()
{
return $this->belongsTo(Issue::class);
}
}
class Issue extends Model
{
public function volume()
{
return $this->belongsTo(Volume::class);
}
}
You should be able to eager load the issue relation and the issue's volume relation when retrieving your articles, like this:
$articles = Article::with(['issue', 'issue.volume'])->get();
and in your view (Assuming you use the name attribute):
{{ $article->issue->volume->name }}
For more information regarding this, look up "Nested Eager Loading" in the documentation

Related

Laravel 5.8 Eloquent querying

I know all the Eloquent model querying is in the Laravel documentation and I have read through them to figure this out but can't seem to work my way around it. I am building a recipe application, and I want to get access to a particular profile picture of a user based on an uploaded recipe.
I have a grid of recipes that have been uploaded by various users. The User and Recipe model are below.
User Model
public function recipes()
{
return $this->hasMany('App\Recipe');
}
Recipe Model
public function user()
{
return $this->belongsTo('App\User');
}
In my recipe grid, I have the following code in a recipe card.
Index Blade/View
#foreach($recipes as $recipe)
<img class="recipeProfilePic" src="/storage/profile_pictures/{{What goes here}}" alt=""><a
href="{{ route('user', $recipe->user_id) }}">
<small>{{$recipe->author}}</small>
</a>
#endforeach
Through the $recipe I can access the name of the creator of that particular recipe like this $recipe->author. I am trying to get access to this specific users profile photo too. I want to get something like this $recipe->author->profile_pic. (profile_pic is a column in my users table).
How would I go about solving this problem in a simple way? I'm a newcomer to coding and am still working on solving these problems myself. Thank you!
You can do it like this:
$recipe->user->profile_pic
You can change the model by rename user to author like this:
public function author()
{
return $this->belongsTo('App\User');
}
or changing view (blade) like this:
#foreach($recipes as $recipe)
<img class="recipeProfilePic" src="/storage/profile_pictures/{{What goes here}}" alt=""><a
href="{{ route('user', $recipe->user_id) }}">
<small>{{$recipe->user->profile_pic}}</small>
</a>
#endforeach

Laravel how to take from another table?

I have a table called "logs" with custom column "auth_id" and i have another table called "users" with same column name "auth_id" and column "username".
How can i take it from "logs" with "logs.auth_id" and get username by "users" table?
Now i'm getting results by:
$match->messages = DB::table('logs')->where('match_id', '=', $match->match_id)->get();
Blade:
#foreach ($match->messages as $message)
{{ $message->auth_id }}:
{{ $message->message }}
Example: Now i'm getting AUTH5556 with {{ $message->auth_id }} but i need to get USERNAME from "users" table by {{ $message->auth_id }}
Don't use joins, this is the whole reason for using something like laravel (eloquent). You need to define a relationship between your models.
On your user model you would define a method
public function logs()
{
return $this->hasMany(Log::class);
}
On your log model
public function user()
{
return $this->belongsTo(User::class);
}
Now you need to make sure on your logs table you have a user_id column.
Now you can simply get the log for example
$log = Log::find($id);
And you can retrieve any information about the user who owns that log, for an example in a blade file.
{{ $log->user->username }}
To get reverse information you need to iterate through the results as the user can have many logs. Eg:
$user = User::find($id);
Then you'd do something like this in your blade
#foreach($user->logs as $log)
{{ $log->column_on_log_you_want }}
#endforeach
You also need to look into eager loading.
This is what makes laravel so clean and nice to use.
Read through the documentation
You need to use JOIN in your query to get username from users table. Here is the link to Laravel manual

Laravel show data

I'm new with Laravel or any MVC.
I created the models, I create the route from web.php, I created the view with Blade, I created the controller and fetched all the data from a single model. Now, I want to make a join or something similar.
I want to get something this:
Name | Section name | Status.
In my user Model I have:
ID | Name | SectionID | Status
In my sections Model I have:
ID | SectionID | Active
Currently I created the controller like this:
public function show($name)
{
if(User::where('name', '=', $name)->exists())
{
return view('profile', ['user'=>User::where('name', $name)->first()]);
}
else
{
return 'User not found';
}
}
And in my Blade I'm getting content like this: {{ $user->name }}
Hmm you have to define the relationship between user and section model.
Please check this thread for how to work with relationships in laravel Laravel Eloquent Relationships.
Then whenever you get the user you can load any relationship that its defined on User model.
In your case you are performing two unecessary database calls, so I would suggest you to check out DRY principle.
Lets say in User has one Section you define the relationship in User model like so:
public function sections(){
return $this->hasOne(Section::class);
}
Then the reverse relationship from section model:
public function user(){
return $this->belongsTo(User::class);
}
So now your method in controller might look something along the lines of this:
public function show($name){
return view('profile', ['user'=>User::with('sections')->where('name', $name)->firstOrFail()]);
}
This way you eagerload the sections that are tied to that user, for more about Laravel eagerloading
Then in the blade you can access any of the attributes from user or section model.

Get commentable class attributes using Baum in Laravel

I am using Laravel Commentable that uses Baum
Post Model
class Post extends Model
{
use Commentable;
....
My user model name is User
Comment table structure:
The user_id stores the user id of the user who commented, commentable_id stores the post id of the post where the comment was placed.
The Comments are working as expected.
I am able to insert comments, delete comments.
To display the comments:
$comments = Comment::orderBy('id', 'desc')->get();
#foreach($comments as $comment)
{{ $comment->user->name }} : {{ $comment->body }}
#endforeach
This gives me the name and the comment by the user in the view.
Question:
How to get the post model attributes from a comment?
{{ $comment->post->slug }} <-this doesn't works
Per the code from this package, you have to use the commentable relation. However, there is no way to be sure that this will be a Post model, this can be any model that is commentable.
An example that checks if the commentable is actualy a post object and shows the slug if so:
#if ($comment->commentable_type === \App\Post::class)
{{ $comment->commentable->slug }}
#endif

LARAVEL 5.3, Get User Name and Role Name (Using Laravel Model Relationships)

Testgrammatical or spelling errors
► clarify meaning without changing it
► correct minor mistakes
► add related resources or links
► always respect the original author
Get the data using eager loading:
$user = User::where('id', $userId)->with('roles')->first();
Then display the data:
{{-- Display full name --}}
{{ $user->first_name.' '.$user->last_name }}
{{-- Display all role names of the user --}}
#foreach ($user->roles as $role)
{{ $role->name }}
#endforeach
I guess relation here is many to many, so you need to change roles() relation to belongsToMany()
If you're using some package with many to many relationship, but you're only attach one role for user, you can display role name with this:
{{ $user->roles->first()->name }}
Also, you could use accessor to get full name:
public function getFullNameAttribute($value)
{
return $this->first_name.' '.$this->last_name;
}
To display full name using accessor:
{{ $user->full_name }}
#foreach($users as $user)
{{$user->name}} {{$user->roles->first()->name}}
#endforeach

Categories