How to manipulate an object in laravel - php

I have a laravel query as the one below:
$campaign = Campaign::with(array('tracks.flights' => function($q) use ($dates)
{
$q->whereRaw("flights.start_date BETWEEN '". $dates['start']."' AND '".$dates['end']."'")->orderBy('start_date')
->with('asset')
->with('comments');
}
))
->with('tracks.group')
->with('tracks.media')
->orderBy('created_at', 'desc')
->find($id);
I am very new to laravel and right now the response from this query returns all the data required including the comments with the comments attributes from the DB.
What i want to achieve is manipulate the comments object so it includes the user name from the users table as the comments table has the user_id only as an attribute.
How can I achieve this? I am very new to laravel.

Your Comment model must have a relationship with the User model, such as:
public function user()
{
return $this->belongsTo('App\User');
}
Now when you are iterating comments you are able to do $comment->user->name or in your case it will be something like this:
#if(!$campaign->tracks->flights->isEmpty())
#foreach($campaign->tracks->flights as $flight)
#if(!$flight->comments->isEmpty())
#foreach($flight->comments as $comment)
{!! $comment->user->name !!}
#endforeach
#endif
#endforeach
#endif
Once you can do this, next step is to understand eager load with eloquent.

Related

Laravel - getting relation in loop - best practices

Just an example:
let's say I have Post model, and the Comment model. Post, of course, have Comments, one-to-many relation.
I have to display list of posts with comments below it.
I'll get my posts in the controller:
$posts = Post::get(), I'll pass it to the blade view and then I'll loop through it
#foreach($posts as $post)
{{ $post->title }}
{{ $post->comments }}
#endforeach
where $post->comments is some relation
public function comments()
{
return $this->hasMany(Comment::class);
}
As we know, that query will be executed many times.
Now my question: how we should optimize it?
Return Cache::remember in the getter?
Get (somehow?) those comments, when getting the posts in one query? Something like join query? I know that I can write that kind of query, but I'm talking about Eloquent's query builder. And then how get the comments within the loop? Wouldn't {{ $post->comments }} call the relation again instead of getting stored data?
Different solution?
You can do $posts = Post::with('comments')->get() to eager load the comments with the post. Read more about it in the documentation: https://laravel.com/docs/5.7/eloquent-relationships#eager-loading
Also, to display the comments you would want to add another foreach loop. It would look something like this:
#foreach($posts as $post)
{{ $post->title }}
#foreach($post->comments as $comment)
{{ $comment->title }}
#endforeach
#endforeach
You’ve probably cached some model data in the controller before, but I am going to show you a Laravel model caching technique that’s a little more granular using Active Record models
Note that we could also use the Cache::rememberForever() method and rely on our caching mechanism’s garbage collection to remove stale keys. I’ve set a timer so that the cache will be hit most of the time, with a fresh cache every fifteen minutes.
The cacheKey() method needs to make the model unique, and invalidate the cache when the model is updated. Here’s my cacheKey implementation:
public function cacheKey()
{
return sprintf(
"%s/%s-%s",
$this->getTable(),
$this->getKey(),
$this->updated_at->timestamp
);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function getCachedCommentsCountAttribute()
{
return Cache::remember($this->cacheKey() . ':comments_count', 15, function () {
return $this->comments->count();
});
}
yes u can do like that in controller
$minutes = 60;
$posts = Cache::remember('posts', $minutes, function () {
return Post::with('comments')->get()
});
in blade u can get like that
#foreach($posts as $post)
{{ $post->title }}
#foreach($post->comments as $comment)
{{ $comment->title }}
#endforeach
#endforeach
for more information read this article

Laravel 5.5: Convert query builder to eloquent

Is there a way to transform this query builder to eloquent?
$transactions = DB::table('transactions')
->join('accounts', 'transactions.account_id', '=', 'accounts.id')
->select('transactions.*', 'accounts.name as account_name')
->paginate(5);
I tried it with One To Many. But it need the find() function so it give me one account's transactions but I need to select all transactions with accounts.name
In comments, you've said you have one to many relationship defined (I assume it's Accounts has many Transactions) and you need to get all transactions with account name, so do this:
Transaction::with('account')->paginate(5);
Where account is relationship:
public function account()
{
return $this->belongsTo(Account::class);
}
Then you'll be able to display the data like this:
#foreach ($transactions as $transaction)
{{ $transaction->id }}
{{ $transaction->account->name }}
#endforeach
You will need to use models to do that.
Transaction model and Account model.
Define their relationships
Create a method in the transaction model to retrieve the related account names.
function accoutNames() { //blablabla }
Do the query in controller, something like that:
Transaction->accountNames();

Laravel 5.3 - HasMany Relationship not working with Join statement

I am trying to retrieve symbols with their comments using hasMany in laravel 5.3
Symbol.php
public function comments() {
return $this->hasMany('App\Comment');
}
Comment.php
public function symbol() {
return $this->belongsTo('App\Symbol');
}
when I run:
$symbols = Symbol::with('comments')->paginate(100);
I get the correct output (lists all symbols with their comments)
#foreach ($symbols as $s)
{{ $s->name }}
#foreach ($s->comments as $c)
{{ $c->body }}
#endforeach
#endforeach
but when I add a join to the statement:
$symbols = Symbol::with('comments')
->join('ranks', 'symbols.id', '=', 'ranks.symbol_id')
->join('prices', 'symbols.id', '=', 'prices.symbol_id')
->paginate(100);
The foreach loop has no comments for every symbol. Any idea why the join would be causing this?
When you are doing joins like this, attributes with the same names will be overwritten if not selected. So select the attributes you need for your code, and nothing else. As shown below.
$symbols = Symbol::with('comments')
->join('ranks', 'symbols.id', '=', 'ranks.symbol_id')
->join('prices', 'symbols.id', '=', 'prices.symbol_id')
->select('symbols.*', 'ranks.importantAttribute', 'prices.importantAttribute')
->paginate(100);
Basicly i think your ids are being overwritten, by the two joins because they also have id fields, i have had a similar problem doing joins, and it breaks relations if the id is overwritten.
And you have to be carefull, all fields who shares names can be overwritten and parsed wrong into the models.

Getting data in a table with matching IDs to the pivot table in Laravel

I've got 3 tables, the users table, the image table, and the favorites table which works sort of like a pivot table, as all it has is ID, image_id, and user_id.
In my user model, I have:
public function FavoritedByMe() {
return $this->hasMany('CommendMe\Models\Favorite', 'user_id');
}
In my favorites controller, I have:
public function getFavorites($username) {
$user = User::where('username', $username)->first();
return view('user.favorites')
->with('user', $user);
}
and this works just fine if I want to get the IDs of all the images I've favorited:
#foreach ($user->FavoritedByMe as $favorite)
{{ $favorite->image_id }}
#endforeach
However, what I'd really like to be able to return the view with the images themselves. Something like:
$favImages = Images::where('id', $user->FavoritedByMe->image_id);
return view('user.favorites')
->with('user', $user)
->with('favImages', $favImages);
Now obviously this won't work, and will return the error:
ErrorException in FavoritesController.php line 54: Undefined property: Illuminate\Database\Eloquent\Collection::$image_id
but perhaps some kind of Eloquent relationship would? I've tried making those work but they just don't "click" in my head.
How could I make this work?
Thanks in advance!
In your Favorite model add this relationship:
public function image()
{
return $this->belongsTo('YourImageModel');
}
Then you can acces the image like this:
#foreach ($user->FavoritedImages as $favorite)
{{ $favorite->image->yourProperty }}
#endforeach
In the laravel's best practices you should call your FavoritedByMe relationship favorites since it's obviously related to the user.

Data from Two tables duplicating on join

I have got two tables , I would use facebook POST as an example.
Post Table
Comment Table
My query
$result = DB::table('posts')
->join('comments', 'posts.post_ID', '=', 'comments.post_ID')
->get();
I will receive an array of posts and comments merge. For each comments that exist , they will have the posts data.
What i want is to be able to do something like
foreach($posts as $post){
foreach($post['comment']{
}
}
Any idea how i can do that?
Something like this should work:
$result = DB::table('posts')
->join('comments', 'posts.id', '=', 'comments.post_id')
->get();
In the view:
#foreach($posts as $post)
{{ $post->post_title }}
{{ $post->message }}
#endforeach
Make sure that, field names in ->join('comments', 'posts.id', '=', 'comments.post_id') are right or change accordingly. post_title/comment_text is used to demonstrate the example, change to it's original table's field name and {{ }} is used in the example to echo the data, if you are not using Blade then use echo $post->post_title instead.
Update::
If you use Eloquent then use:
// Assumed you have defined comments as relationship method
$posts = Post::with('comments')->get(); // it's faster and called eager loading
Then in the view:
#foreach($posts as $post)
{{ $post->post_title }}
#foreach($post->comments as $comment)
{{ $comment->message }}
#endforeach
#endforeach
I will receive an array of posts and comments merge. For each comments that exist , they will have the posts data.
This is correct SQL behavoir when using a join. You will get the contents of both the rows inside the posts and comments rows on your JOIN.
According to Laravel 4.2's documentation on the join method, the parameters of the join function are:
join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
Using an INNER JOIN, you are only going to get rows returned to you with your query (using an inner join) if you have a comment for all of the posts that you want data from. Additionally, with your INNER JOIN, if there is no comment on your post, you will not get any posts returned to you.
Also, you are not going to be able to separate all of your comments from your posts, which may mean that you are getting results returned for posts that you
The simple way to solve this for you would be to make two eloquent models:
class Post extends Eloquent {
protected $table = 'posts';
public function getComments() {
return $this->hasMany('Comments', 'post_id');
}
}
class Comments extends Eloquent {
protected $table = 'comments';
}
From that you can query for all of the posts with eager loading:
$posts = Post::with('comments')->get();
and inside your view, you go:
foreach($posts as $post) {
// echo the $post? (title, author etc)
foreach($post->comments() as $comment) {
// echo the $comment? (author, content etc)
}
}

Categories