Im building a app the shows information of a survey results. In each survey i have questions, and each question have his answers.
But im having some issues on building the table, the header table and the body is build dynamacly, where the header is the questions, and the body are the answers.
Examle of my code table:
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
#foreach($survey->answers->groupBy('email')->first() as $answer)
<th>{{$answer->question->internal_name}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($survey->answers->groupBy('email') as $answer)
<tr>
#foreach($answer as $a)
<td>{{$a->answer}}</td>
#endforeach
</tr>
#endforeach
</tbody>
<tfoot>
#foreach($survey->answers->groupBy('email')->first() as $answer)
<th>{{$answer->question->internal_name}}</th>
#endforeach
</tfoot>
</table>
The only problem that im having is the syncronization between the header label questions and above that are the answers, sometimes the answer if a question is sort in a diferent order, for example is not in the correct position.
Cant figure out what im doing wrong, above i leave the tables, maybe someone can have a idea what im doing wrong.
Tables:
surveys:
- id;
- name;
questions:
- id;
- survey_id;
- label;
- internal_name;
answers:
- id;
- survey_id;
- question_id;
- answer
- email;
Question Model:
class Question extends Model
{
public function survey()
{
return $this->belongsTo(Survey::class);
}
public function answers() {
return $this->hasMany(Answer::class);
}
public function oneAnswer(){
return $this->hasOne(Answer::class);
}
}
Answer Model:
class Answer extends Model
{
public function survey() {
return $this->belongsTo(Survey::class);
}
public function question() {
return $this->belongsTo(Question::class);
}
}
Screenshot
According to my understanding, do an order by question_id. Also noticing that you are querying three times, I suggest query one time & store it in a variable and use it.
#php
$results = $survey->answers->groupBy('email')->orderBy('question_id');
#endphp
...
#foreach($results->first() as $answer)
...
Related
I have added Datatables in my application and i wanted to make the ID of each entry to be a hyperlink to the edit page in order for a user to be able to edit their Post. But i am getting a 404 Not Found error
I tried updating my route file but i don't get the correct result and i cannot figure what i am doing wrong
My web php file has:
Route::get('edit','PostsController#edit');
The index for my posts is
<table class="display" id="postsTable">
<thead>
<tr>
<td>ID</td>
<th>Title</th>
<th>Slug</th>
<th>Subtitle</th>
<th>Content</th>
<th>Category</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->id}}</td>
<td>{{$post->title}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->content}}</td>
<td>{{$post->category_id}}</td>
</tr>
#endforeach
</tbody>
And the PostsController edit function is:
public function edit($id)
{
$posts = Post::findOrFail($id);
return view('posts.edit',compact('posts'));
}
I tried searching online and playing a bit with my routes but i managed to make things worse rather than solving my issue. any help is much appreciated!
You can set Route name like below
Route::get('edit/{id}','PostsController#edit')->name('edit_post');
Then in HTML section use it like below
<tbody>
#foreach($posts as $post)
<tr>
<td>Edit Post</td>
<td>{{$post->title}}</td>
<td>{{$post->slug}}</td>
<td>{{$post->subtitle}}</td>
<td>{{$post->content}}</td>
<td>{{$post->category_id}}</td>
</tr>
#endforeach
</tbody>
You should add some validation on client side to be sure that you have data so you can add your code inside if condition like below
#if ($posts ?? count($posts) ?? false)
// Your code here
#endif
Are you sure there is a record in your database that matches the $id that came with the get method? If there is no matching record, findOrFail($id) returns 404 pages.
In your controller check, the posts are found or not
public function edit($id)
{
$posts = Post::findOrFail($id);
// check post are found or not
if(!isset($posts)){
# show your errors if data not found
}
return view('posts.edit',compact('posts'));
}
In my application, i send out surveys and group and count similar and non-similar responses. This is how my group and count is working now
NB: Take this instance as if the survey was answered by 2 clients.
Client 1 and Client 2 both selected Good for question 1
Responses
question Ans
How would you describe my services? Good (2)
How would you describe my services? Good (2)
Gender Male(1)
Gender Female(1)
How can take out the redundancy. the question repeats itself and also, when the answers repeat itself with the count.
Responses
question Name Ans
How would you describe my services? Good (2)
Gender Male(1), Female(1)
Model
public function count_answers()
{
return $this->hasMany(Answer::class)->select('answer', DB::raw('count(*) as counter'))->groupBy('answer');
}
View
#forelse ($data->questions as $item)
#foreach ($item->answers as $answer)
<tr>
<td width="30%">{{ $item->title }}</td>
<td>
#foreach ($item->count_answers as $answer)
<div>{{$answer->answer}} ({{$answer->counter}})</div>
#endforeach
</td>
</tr>
#endforeach
Controller
public function view_survey_response(Survey $data)
{
$data = Survey::where('id', $data->id)->where('user_id', Auth::user()->id)->first();
return view('answer.response', compact('data'));
};
I'm working on updating a laravel blade template to insert some database info into an html table. IN order to do this, I'm having to add new data to the controller for this blade and that's where I'm having some troubles.
I'm still trying to understand more with laravel, so I'm thinking my syntax or methods of creating this data are incorrect but I just can't put my finger on it right now.
In my function below, the $calls_allowed portion was already existing and it works on the page currently. I created the $contact_events portion of the function and that's where my problem is.
IN my view, I created a foreach loop and if statement around the html table in question. The table loads, but it's empty even though there are records in the database for the dealer.
I'm trying to say
if $dealer-> id matches contact_events.dealer_num, load all records for that dealer
contact_events is the table and dealer_num is the column I'm matching, then I'm trying to load the columns from that table (updated_at,method,notes) into the html table.
The affected code is below. The view/route/controller work, it's just this function I'm creating that isn't loading data. Any help is much appreciated.
Controller code:
public function show($id)
{
$d = Dealer::find($id);
if(!$d){
\Session::flash('warning_message', 'Sorry that resource can not be found.');
return redirect()->route('account.dealer.index');
}
$calls_allowed = DB::table('dealers.dealers')->
where('dealer_num', $id)->
pluck('calls_allowed');
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
if(!empty($calls_allowed)){
$d->calls_allowed = $calls_allowed[0];
} else {
$d->calls_allowed = null;
}
return view('Account.Dealer.show')->with('dealer', $d);
}
View code:
<thead>
<tr>
<th>Contacted Date</th>
<th>Type of Contact</th>
<th>Call Notes</th>
</tr>
</thead>
#foreach($dealer->contact_events as $events)
#if($events->dealer_num = $dealer->id)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endif
#endForeach
It looks like you are not assigning the data to the object after retrieving from database.
$contact_events = DB::table('dealers.contact_events')->
where('dealer_num', $id)->
pluck('updated_at', 'method', 'notes');
// add this
$d->contact_events = $contact_events;
This seems like a perfect time to use the power of Laravel's Eloquent ORM...
Check out the with and has in the Laravel docs
This will require some finessing based on your needs, but it will be something like this:
$d = Dealer::where('id', '=', $id)
->with('contact_events')->first();
This uses Eloquent to get all of the contact_events that belong to the dealer with the $id.
Then you can do something like this
note: this assumes that calls_allowed is a record on the dealer table. if I misunderstood that, you can still run than you can include that just as you have it.
#if(!is_null($dealer->calls_allowed)
#foreach($dealer->contact_events as $events)
<tbody>
<tr>
<td>{{$events->updated_at}}</td>
<td>{{$events->method}}</td>
<td>{{$events->notes}}</td>
</tr>
</tbody>
#endForeach
#endif
Sorry for my English.
I want to make a record that would be deduced me the sum of all my orders, that is, folded string of orders and drew grouped by orders.
I have created a model "Sale", which comprises method AmountOrder
public function AmountOrder()
{
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(price*quantity) as total_sales'))
->value('total_sales');
return $AmountOrder;
}
and to deduce the code like this
#foreach ($sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->client->name }}
</td>
<td>
{{$sale->date}}
</td>
<td>
{{$sale->AmountOrder($sale)}}
</td>
<td>
{{$sale->debt($sale)}}
</td>
<td>
{{$sale->date_of_issue}}
</td>
</tr>
#endforeach
But the problem is that the query is performed on each line. I'm new to Laravel, but thought maybe you can solve this problem somehow more beautiful?
Thank you very much in advance!
You are probably talking about the Eager Loading.
From the docs:
When accessing Eloquent relationships as properties, the relationship data is "lazy loaded". This means the relationship data is not actually loaded until you first access the property. However, Eloquent can "eager load" relationships at the time you query the parent model. Eager loading alleviates the N + 1 query problem.
However, you will be not able to use the Eager Loading now, with this code in the AmountOrder method.
A simple google search, also, led me to this example of Eager Loading with aggregate functions/relationships.
It will be probably a good start to think and implement your solution.
you have wrong in your select :
$AmountOrder = DB::table('goods')
->join('sale_lines', 'sale_lines.good_id', '=', 'goods.id')
->where('sale_id', $this->id)
->select(DB::raw('SUM(sale_lines.price*sale_lines.quantity) as total_sales'))
->value('total_sales');
My relationship
class Sale extends Model
{
//Получаем товар в этой продаже
public function good()
{
return $this->belongsTo('App\Good');
}
}
class Good extends Model
{
//В каких закупках был этот товар
public function purchases()
{
return $this->hasMany('App\Purchase');
}
//Продажи с этим товаром
public function sales()
{
return $this->hasMany('App\Sale');
}
}
Is it correct?
In my model i create method
public function AmountOrderRelation()
{
return $this->belongsTo('App\Good')
->selectRaw('sum(price) as aggregate, id')
->groupBy('id');
}
In controller
$new_sales = Sale::with('AmountOrderRelation')->get();
#foreach ($new_sales as $sale)
<tr>
<td class="table-text"><div>{{ $sale->id }}</div></td>
<td>
{{ $sale->AmountOrderRelation }}
</td>
</tr>
#endforeach
But my relations is null. What's my mistake?
I did it!
public function AmountOrder()
{
return $this->HasOne('App\SaleLines')
->join('goods', 'sale_lines.good_id', '=', 'goods.id')
->selectRaw(DB::raw('SUM(price*quantity) as aggregate, sale_id'))
->groupBy('sale_id');
}
public function getAmountOrderAttribute()
{
// if relation is not loaded already, let's do it first
if ( ! array_key_exists('AmountOrder', $this->relations))
$this->load('AmountOrder');
$related = $this->getRelation('AmountOrder');
// then return the count directly
return ($related) ? (int) $related->aggregate : 0;
}
And in controller
$sales = Sale::with('AmountOrder')->get();
I'm stuck trying to figure out how to get my posts to display under the same subject. I'm currently porting over procedural code where posts have a subject_id that linked to the subject id in the db.
Example:
Subject 1
Related post 1
Related post 2
Subject 2
Related post 1
Related post 2
The area I don't understand fully comprehend after looking at similar Stack posts is where the subject/post are connected in the model. Right now the code is just showing all subjects and posts but not displaying the posts assigned to the same subject.
Help in understanding what I am doing wrong would be appreciated. Thanks.
Controller
public function index()
{
// Get all subjects
$subjects = Subjects::all();
// $subjects = Subjects::with('pages')->get();
$pages = Pages::all();
// Load the view and pass in the subjects
// return View::make('index')->with('subjects', $subjects)->with('pages', $pages);
return View::make('index', compact('subjects', 'pages'));
}
Subjects Model
class Subjects extends Eloquent {
public function pages ()
{
return $this->hasMany('Pages', 'subject_id');
}
}
Posts Model
class Pages extends Eloquent {
public function subjects ()
{
return $this->belongsTo('Subjects', 'id');
}
}
View
#foreach ($subjects as $subject)
<tr>
<td> {{ $subject->menu_name }} </td><br>
</tr>
#foreach ($pages as $page_id)
<tr>
<li>{{ $page_id->menu_name }}</li><br>
</tr>
#endforeach
#endforeach
You can load each subject's pages by calling $subject->pages in your loop:
Controller:
public function index()
{
return View::make('index')->withSubjects( Subjects::with('Pages')->get() );
}
Note: For efficiency, we're calling with('Pages') in the controller, to eager load the pages.
View:
#foreach ($subjects as $subject)
<tr>
<td> {{ $subject->menu_name }} </td>
</tr>
#foreach ($subject->pages as $page)
<tr>
<li>{{ $page->menu_name }}</li>
</tr>
#endforeach
#endforeach