Laravel 6 relation with() - eloquent

I have a Posts model which has many Comments and every comment has one User model.
If I run
#foreach( $post->comments as $comment )
<div>{{ $comment->text }} <br>{ $comment->user->name }}</div>
#endforeach
it generates one query to user for every loop in comments foreach. How to write this code so the Laravel makes only one query for all users?
Controller code looks like
public function detail(Post $post)
{
return view('home.detail')->with([
'post' => $post->with('comments', 'comments.user')->get()->first()
]);
}
Thanks a lot.

Related

Retrieve 'username' from Articles table

I have two tables, 'users' and 'articles'. Articles have a column 'user_id' which is a foreign key that references the user_id in 'users'.
I have in the Articles model this function which should return the user data:
public function user()
{
return $this->belongsTo('App\User');
}
And this works fine when I pass my articles to my viewer and call it in blade template:
#foreach($articles as $article)
<p>{{$article->user->name}}</p>
#endforeach
But I am trying to use the RESTful approach, so I am rather retrieving my data from JS (VueJS)
axios.get('/api/articles')
that should fire my Controller's function:
public function index()
{
$books = bookpost::all();
return $books;
}
So I was wondering if there's a way to append the user names to the JSON array of articles before returning it because in JS I couldn't get to find a way to get the username.
You can use "eager loading" in your query to help:
$books = bookpost::with('user')->get();
You may even eager load nested relationships:
$books = bookpost::with('user.friends')->get();
Have a look at the documentation for further help.

How to generate form using Illuminate/HTML and database values in Laravel?

I saw this question: Generate drop-down list input with values from DB table, but the answer was not clear.
So, how can I generate form using Illuminate/HTML and database values in Laravel?
It's this simple.
First, you have to pass an array with the select values from the controller:
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$categories = Category::lists('name','id');
return view('myformview', compact('categories'));
}
Where "Category" is the model I want to retrieve data from. Note I am passing two values to the array. The first one is the text will be displayed in the select, and the second one is the value of the option.
Let's see now the form:
{!! Form::label('category_id', 'Category:') !!}<br>
{!! Form::select(
'category_id',
$categories
)
!!}
The first parameter of Form::select is the name of the select. The second one is the array with the options values.
In my particular case I get back this HTML code:
<select id="category_id" name="category_id">
<option value="5">First category</option>
<option value="6">Second category</option>
<option value="7">Third category</option>
</select>
I hope this will be helpful for you. I tested it in Laravel 5

how to access eloquent eager loading collection in blade template?

I fetch posts from a database with answers to them and the post author (user).
The result looks good in dd($posts). I can see all needed information.
the model and relationships:
class Post extends Model {
public function postanswers()
{
return $this->hasMany('Myapp\Postanswer','post');
}
public function user()
{
return $this->belongsTo('Myapp\User','user','id');
}
}
the query:
$posts = Post::with('user','postanswers')->paginate(20);
How can I loop through the results in a blade template, access the user's username and count the post answers? Here is one thing I tried, but nothing seems to work:
#foreach($posts as $post)
{{ $post->user->username }}
#endforeach
I can't find out what I am doing wrong.
edit:
I found that {{ $post->User->username }} works. uppercase U

Laravel4 Repopulate Search Form after submit

I have a get method search form with a field like this:
{{ Form::text("name", null, array('class' => 'form-control')) }}
My controller look like this:
public function index()
{
...
$result= $this->repo->search($data, $page, $perPage);
return View::make('index', compact('result'));
}
The route look like this:
Route::get('/search', 'controller#index');
and the form:
<form action="/search" id="searchForm" class="search-form">
I want to repopulate the name field to keep his value even after the search submit.
To do this I added to my controller before the view::make:
Input::flash();
I have problems with this flashing, because when I open one of my result line from the search for editing, the old input is not empty and cause false values on the form model binding of this editing page.
How can I repopulate the search form in an other way ? (No model binding possible for this search form)
Finally, I found what I was searching:
{{ Form::text("name", Input::get("name"), array('class' => 'form-control')) }}
With all the magical in Laravel, I thought there is a possibility to do this automatically, but this what I was searching.

Doctrine join query access problem

i have two tables pages and page_desc and have a relation
$this->hasMany('Model_PagesDesc as PageDesc', array(
'local' => 'id',
'foreign' => 'pages_id'));
i have a query
return Doctrine_Query::create()
->select('m.*, d.*')
->from('Model_Pages m')
->leftJoin('m.PageDesc d')
->execute();
NOW WHEN QUERY EXECUTES. iN VIEW WHEN I TRY TO GET FIELD VALUE OF SCEOND TABLE IT RETURNS SOME INTEGER INSTEAD OF ACUAL VALUE IN FIELD
<?php echo $pages->PageDesc->content;?>
If youre using hasMany then you should Model_Pages::PagesDesc will be a Doctrine_Collection not a Model_PagesDesc instance. Im not sure but i would assume that the default behavior of the collection is to return the count of elements in the collection when converted to string, thus the integer. You need to either loop over the collection or get a specific item.
<?php echo $pages->PageDesc->getFirst()->content; ?>
OR
<?php foreach($pages->PageDesc as $desc): ?>
<?php echo $desc->content; ?>
<?php endforeach; ?>
Or you could write a custom collection for this model that returns concat of the content fields for every element in the collection.
However it seemdsthat a page shouldnt really have more than one description should it? You might want to consider using a 1-1 relation or just making the description a column on your page model.