Var emptied from child view to parent view Laravel - php

I got a really strange behavior in my views. I have a parent view called "access.blade.php" and child view "survey.blade.php".
I instanciated 2 vars in the parent view which are empty arrays.
I populate them in the child view but when i var_dump them in the parent view after the include of the child view, my var are empty...
here is the parent view :
#extends('template')
#section('title')
Compile result
#stop
#section('content')
<div id="access" class="container-fluid main-content">
<div class="row">
<div class="col-xs-6 col-md-push-3 col-xs-push-3">
<div class="page-title white-text text-center">
<h1>Access Report</h1>
</div>
<div class="widget-container fluid-height clearfix">
<?php
$session = Sessions::find($params['session_id']);
$userNotSeen = [];
$userSeen = [];
?>
<div class="heading">
<button class="btn btn-success btn-xl pull-right" role="button" data-toggle="modal" data-target="#complianceModal">Compliance</button>
Access Report for
{{ isset($result->content->display_name) ? $result->content->display_name : $result->content->title }}
<p>
Journey: {{ $session->location_id != null ? $session->location->city : $session->place }}
</p>
</div>
<div class="row text-center"></div>
<div class="row">
<div class="col-sm-offset-1 col-sm-10">
#if($result != null)
#if($result->content_type == 1)
#include('contents.partials.access.tasklist')
#elseif($result->content_type == 2)
#include('contents.partials.access.resources')
#elseif($result->content_type == 3)
#include('contents.partials.access.survey')
#elseif($result->content_type == 4)
#include('contents.partials.access.feedback')
#elseif($result->content_type == 5)
#include('contents.partials.access.memo')
#elseif($result->content_type == 6)
#include('contents.partials.access.gear')
#elseif($result->content_type == 7)
#include('contents.partials.access.sinsim')
#elseif($result->content_type == 8)
#include('contents.partials.access.changr')
#endif
#else
<p class="text-center">{{ $errors }}</p>
#endif
<pre>
{{ var_dump($userNotSeen) }}
</pre>
<pre>
{{ var_dump($userSeen) }}
</pre>
</div>
</div>
</div>
</div>
</div>
</div>
#include('contents.partials.modal')
#stop
And here is my child view
<table class="table">
<thead>
<tr>
<th>Name</th>
<th class="text-center">Viewed</th>
<th class="text-center">Submitted</th>
<th class="text-center">Personnal Results</th>
</tr>
</thead>
<tbody>
#if(isset($result->data))
#forelse($result->data as $key => $value)
<tr {{ $value->view == 0 ? 'class="notyetseen"' : ''; }}>
<td>{{ $value->fullname }}</td>
<td class="text-center">{{ $value->view == 0 ? 'No' : 'Yes' }}</td>
<td class="text-center">{{ $value->done == 0 ? 'No' : 'Yes' }}</td>
<td class="text-center">
Get results
</td>
</tr>
<?php
if($value->view == 0) {
array_push($userNotSeen, $key);
} else {
array_push($userSeen, $key);
}
?>
#empty
<tr><td colspan="3" class="text-center">{{ $errors }}</td></tr>
#endforelse
#else
<tr><td colspan="3" class="text-center">No participants for this journey</td></tr>
#endif
</tbody>
</table>
I have an idea about the why it doesn't work: maybe the parent view is loaded completly before the child view, so my var are not yet populated.
If it is the case, is there any solution?

First of all, never EVER include logic in your templates. Move this logic to your controller and pass results to a view. Templates are only for displaying your data.
If you have to use <?php in your Blade template, you are doing something wrong.
Second, Blade compiles your templates separately. It is not a simple include(__child_template__). That's why while compiling each of your templates, Blade works with completely different variable scopes and $userNotSeen in access.blade.php template is not the same as in your survey.blade.php.

Related

Paginate one page with different tabs Laravel

I want to paginate in a blade file different tabs , each tabs show different collections of object but each time i go to next page in one page it redirects to the first tab and also paginate each tab not just the one i wanted to paginate.
Blade Part Where i have tabs
<div class="container">
<div class="section-bg-color">
<div class="row">
<div class="col-lg-12">
<!-- My Account Page Start -->
<div class="myaccount-page-wrapper">
<!-- My Account Tab Menu Start -->
<div class="row">
<div class="col-lg-3 col-md-4">
<div class="myaccount-tab-menu nav" role="tablist" id="myTab">
<i class="fa fa-dashboard"></i>Dashboard
<i class="fa fa-user"></i>Gestione Utenti
<i class="fa fa-book"></i>Gestione Fumetti
<i class="fa fa-map-marker"></i>Gestione Recensione
</div>
</div>
<!-- My Account Tab Menu End -->
<!-- My Account Tab Content Start -->
<div class="col-lg-9 col-md-8">
<div class="tab-content" id="myaccountContent">
<!-- Single Tab Content Start -->
<div class="tab-pane fade show active" id="dashboad" role="tabpanel">
<div class="myaccount-content">
<h5>Dashboard</h5>
<div class="welcome">
<p>Ciao, <strong>{{ $user->username }}</strong>! (Non sei <strong>{{ $user->username }}</strong>? Logout)</p>
</div>
<p class="mb-0">I tuoi dati:</p>
<p class="mb-0">E-mail: <strong>{{ $user->email }} </strong></p>
</div>
<div class="myaccount-content">
#php
$notifications = \App\Http\Controllers\NotificationController::getNotification($user->id);
#endphp
<h5>Notifiche</h5>
#if($notifications->count() < 1)
<div class="myaccount-content">
<h5>Non ci sono ancora notifiche</h5>
</div>
#else
<div class="myaccount-table table-responsive text-center">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Data</th>
<th>testo</th>
<th>stato</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($notifications as $notification)
<tr>
<td>{{ $notification->date }}</td>
<td>
#if(strlen($notification->notification_text) > 50 )
#php
$subnotification = substr($notification->notification_text, 0, 50)
#endphp
{{ $subnotification }}...
#else
{{ $notification->notification_text }}
#endif
</td>
#if($notification->state == 1)
<td>
Letto
</td>
<td>
View
</td>
#else
<td>
Non letto
</td>
<td>
View
</td>
#endif
</tr>
#endforeach
</tbody>
</table>
</div>
#endif
</div>
</div>
<!-- Single Tab Content End -->
#if(session('message'))
{{session('message')}}
#endif
<!-- Single Tab Content Start -->
<div class="tab-pane fade" id="users" role="tabpanel">
<div class="myaccount-content">
<h5>Utenti</h5>
<div class="myaccount-table table-responsive text-center">
<table class="table table-bordered">
<thead class="thead-light">
<tr>
<th>Nickname</th>
<th>Phone</th>
<th>Email</th>
<th>Tipologia</th>
<th>Elimina</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{$user->username}}</td>
<td>{{$user->phone_number}}</td>
<td>{{$user->email}}</td>
#if($user->hasGroup('il gruppo degli utenti'))
<td>Utente</td>
#else
<td>Venditore</td>
#endif
<td><a class="btn btn-danger" onclick="return myFunction();" href="{{route('user-delete', $user->id)}}"><i class="fa fa-trash"></i></a></td>
<script>
function myFunction() {
if(!confirm("Sei sicuro di voler eliminare questo utente"))
event.preventDefault();
}
</script>
</tr>
#endforeach
{{ $users->links() }}
</tbody>
</table>
</div>
</div>
</div>
<!-- Single Tab Content End -->
<!-- Single Tab Content Start -->
<div class="tab-pane fade" id="comics" role="tabpanel">
<div class="myaccount-content">
<h5>Fumetti</h5>
<div class="myaccount-table table-responsive text-center">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>Titolo</th>
<th>ISBN</th>
<th>Quantità</th>
<th>Utente</th>
<th>Elimina</th>
</tr>
</thead>
<tbody>
#foreach($comics as $comic)
#php
$userNeed = App\User::where('id','=',$comic->user_id)->first();
#endphp
<tr>
<td>{{$comic->comic_name}}</td>
<td>{{$comic->ISBN}}</td>
<td>{{$comic->quantity}}</td>
<td>{{$userNeed->username}}</td>
<td><a class="btn btn-danger" onclick="return myFunction();" href="{{route('comic-delete', $comic->id)}}"><i class="fa fa-trash"></i></a></td>
<script>
function myFunction() {
if(!confirm("Sei sicuro di voler eliminare questo fumetto"))
event.preventDefault();
}
</script>
</tr>
#endforeach
{{ $comics->links() }}
</tbody>
</table>
</div>
</div>
</div>
<!-- Single Tab Content End -->
<!-- Single Tab Content Start -->
<div class="tab-pane fade" id="reviews" role="tabpanel">
<div class="myaccount-content">
<h5>Recensione</h5>
<div class="myaccount-table table-responsive text-center">
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>Titolo</th>
<th>Fumetto</th>
<th>Recensore</th>
<th>Elimina</th>
</tr>
</thead>
<tbody>
#foreach($reviews as $review)
#php
$userReview = App\User::where('id','=',$review->user_id)->first();
$comicReview = App\Comic::where('id','=',$review->comic_id)->first();
#endphp
<tr>
<td>{{$review->review_title}}</td>
<td>{{$comicReview->comic_name}}</td>
<td>{{$userReview->username}}</td>
<td><a class="btn btn-danger" onclick="return myFunction();" href="{{route('review-delete-local', $review->id)}}"><i class="fa fa-trash"></i></a></td>
<script>
function myFunction() {
if(!confirm("Sei sicuro di voler eliminare questa recensione"))
event.preventDefault();
}
</script>
</tr>
#endforeach
{{ $reviews->links() }}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div> <!-- My Account Tab Content End -->
</div>
</div> <!-- My Account Page End -->
</div>
</div>
</div>
</div>
</div>
And this is my route
Route
Route::get('/adminArea', function () {
$user = \Illuminate\Support\Facades\Auth::user();
$users = \App\User::where('username','!=','admin')->orderBy('username', 'asc')->paginate(12);
$comics =Comic::orderBy('comic_name', 'asc')->paginate(12);
$reviews = \App\Review::orderBy('review_title', 'asc')->paginate(12);
return view('adminPanel')
->with(compact('user'))
->with(compact('users'))
->with(compact('comics'))
->with(compact('reviews'));
})->name('AdminAccount');
In the end what i want to do is to paginate each tab differently meaning if a put the next on the comics i don't want to show also in the user tab the second page of user. The problem is that it use the same pagination url for each tabs so i was wondering if the solution is to give each tab an indipendent url
It redirects to the first tab because you use javascript tabs with active class added to first tab. To resolve problem with tabs you need to change for each tabs nav to:
<a href="#dashboad" class="{{ (Route::currentRouteName() == 'YOUR-ROUTE-NAME) ? 'active' : '' }}" ...
Also here:
<!-- Single Tab Content Start -->
<div class="tab-pane fade show {{ (Route::currentRouteName() == 'YOUR-ROUTE-NAME) ? 'active' : '' }}"...
But your problems with paginations will remain.
Here are 2 solutions:
Use JS tabs and get data via Ajax request.
Use 4 separated routes for each collection and add routes to tabs corresponding above example.
I hope it was clear.
Solution look like this.
Navigation code:
<div class="myaccount-tab-menu nav" role="tablist" id="myTab">
<i class="fa fa-dashboard"></i>Dashboard
<i class="fa fa-user"></i>Gestione Utenti
<i class="fa fa-book"></i>Gestione Fumetti
<i class="fa fa-map-marker"></i>Gestione Recensione
</div>
Also for each tab add, don't forget to change route name for each:
<!-- Single Tab Content Start -->
<div class="tab-pane fade show {{ (Route::currentRouteName() == 'dashboard') ? 'active' : '' }}" id="dashboad" role="tabpanel">
Route code:
Route::get('/dashboard', function () {
$user = \Illuminate\Support\Facades\Auth::user();
return view('adminPanel')->with(compact('user'));
})->name('dashboard');
Route::get('/users', function () {
$users = \App\User::where('username','!=','admin')->orderBy('username', 'asc')->paginate(12);
return view('adminPanel')->with(compact('users'));
})->name('users');
Route::get('/comics', function () {
$comics =Comic::orderBy('comic_name', 'asc')->paginate(12);
return view('adminPanel')->with(compact('comics'));
})->name('comics');
Route::get('/reviews', function () {
$reviews = \App\Review::orderBy('review_title', 'asc')->paginate(12);
return view('adminPanel')->with(compact('reviews'));
})->name('reviews');

Is there any function to stop foreach loop? [duplicate]

This question already has answers here:
How to stop a loop PHP
(4 answers)
Short circuit Array.forEach like calling break
(30 answers)
How to break a foreach loop in laravel blade view?
(5 answers)
Closed 3 years ago.
I'm setting up a loop whenever i tried to print table first row print good with category name and then next row print table with ONE tr(row) data and closed the tag and again start new row and print next data with one row...
i want to print all data with respect to its category name without break multiple table
#if( ! empty($packages) )
#php
$serviceId=null;
#endphp
#foreach($packages as $package)
#if(is_null($serviceId))
<!--CATEGORY NAME PRINT-->
<div class="row" id="">
<div class="col-sm-12">
<div class="well wellHeader">
<h2>{{ $package->service->name }}</h2>
</div>
</div>
</div>
<!--CATEGORY NAME PRINT-->
#php
$serviceId=$package->service->id
#endphp
#endif
#if($serviceId != $package->service_id)
<!--CATEGORY NAME PRINT-->
<div class="row" id="">
<div class="col-sm-12">
<div class="well wellHeader">
<h2>{{ $package->service->name }}</h2>
</div>
</div>
</div>
<!--CATEGORY NAME PRINT-->
#php
$serviceId = $package->service_id
#endphp
#endif
<!--SERVICE NAME TABLE-->
<div class="row">
<div class="col-sm-12">
<div class="well">
<div class="table-responsive">
<table class="table table-striped table-sm ">
<thead>
<tr>
<th>#lang('general.package_id')</th>
<th>#lang('general.name')</th>
<th>#lang('general.price_per_item') {{ getOption('display_price_per') }}</th>
<th>#lang('general.minimum_quantity')</th>
<th>#lang('general.maximum_quantity')</th>
<th>#lang('general.description')</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{ $package->id }}</td>
<td>{{ $package->name }}</td>
<td>#php $price = isset($userPackagePrices[$package->id]) ? $userPackagePrices[$package->id] : $package->price_per_item;
#endphp
{{ getOption('currency_symbol') . number_formats(($price * getOption('display_price_per')),2, getOption('currency_separator'), '') }}</td>
<td>{{ $package->minimum_quantity }}</td>
<td>{{ $package->maximum_quantity }}</td>
<td>{{ $package->description }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
!--SERVICE NAME TABLE-->
#endforeach
#else
No Record Found
#endif
You can create an extra array to map this,
In method
$packagesNew = [];
foreach($packages as $k => $v)
{
$packagesNew[$v->service->name]['name'] = $v->service->name;
$packagesNew[$v->service->name]['id'] = $v->service->id;
$packagesNew[$v->service->name]['service_id'] = $v->service_id;
$packagesNew[$v->service->name]['data'][] = $v;
}
pass packagesNew to view
Then I made changes in view, please check.
#if( ! empty($packagesNew) )
#php
$serviceId=null;
#endphp
#foreach($packagesNew as $k => $package)
#if(is_null($serviceId))
<!--CATEGORY NAME PRINT-->
<div class="row" id="">
<div class="col-sm-12">
<div class="well wellHeader">
<h2>{{ $k }}</h2>
</div>
</div>
</div>
<!--CATEGORY NAME PRINT-->
#php
$serviceId=$package['id'];
#endphp
#endif
#if($serviceId != $package['service_id'])
<!--CATEGORY NAME PRINT-->
<div class="row" id="">
<div class="col-sm-12">
<div class="well wellHeader">
<h2>{{ $k }}</h2>
</div>
</div>
</div>
<!--CATEGORY NAME PRINT-->
#php
$serviceId = $package['service_id'];
#endphp
#endif
<!--SERVICE NAME TABLE-->
<div class="row">
<div class="col-sm-12">
<div class="well">
<div class="table-responsive">
<table class="table table-striped table-sm ">
<thead>
<tr>
<th>#lang('general.package_id')</th>
<th>#lang('general.name')</th>
<th>#lang('general.price_per_item') {{ getOption('display_price_per') }}</th>
<th>#lang('general.minimum_quantity')</th>
<th>#lang('general.maximum_quantity')</th>
<th>#lang('general.description')</th>
</tr>
</thead>
<tbody>
#foreach($package['data'] as $k1 => $v1)
<tr>
<td>{{ $v1->id }}</td>
<td>{{ $v1->name }}</td>
<td>#php $price = isset($userPackagePrices[$v1->id]) ? $userPackagePrices[$v1->id] : $v1->price_per_item;
#endphp
{{ getOption('currency_symbol') . number_formats(($price * getOption('display_price_per')),2, getOption('currency_separator'), '') }}</td>
<td>{{ $v1->minimum_quantity }}</td>
<td>{{ $v1->maximum_quantity }}</td>
<td>{{ $v1->description }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
!--SERVICE NAME TABLE-->
#endforeach
#else
No Record Found
#endif

Undefined variable: user_id in Laravel view

The Routes
Route::get('/adminContacts/{user_id}', 'AdminContactsController#index')->name('adminContacts.index')->middleware('is_admin');
Route::get('/adminContacts/{user_id}/create', 'AdminContactsController#create')->name('adminContacts.create')->middleware('is_admin');
adminContactController
public function index($user_id)
{
// Confirm User exists
User::findOrFail($user_id);
$filter = request('filter', NULL);
$contacts = NULL;
if ($filter == NULL)
$contacts = Contacts::query()->where('owner_id', $user_id)->sortable()->paginate(5);
else
$contacts = Contacts::query()->where('owner_id', $user_id)->where('name', 'like', '%'.$filter.'%')
->orWhere('number', 'like', '%'.$filter.'%')
->sortable()->paginate(5);
return view('adminContacts.index')->withContacts($contacts)->withUserId($user_id);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create($user_id)
{
return view('adminContacts.create')->withUserId($user_id);
}
index.blade.php
<div class="container">
<h1 class="jumbotron">Sample Phone Book</h1>
Add Contact
</div>
<!--Search Field -->
<div class="container">
<form method="GET" action="{{ route('adminContacts.index') }}">
<input type="text" name='filter' class='input' placeholder='Search' value="{{ request('filter') }}">
#if (request('filter'))
<a class="btn btn-primary btn-sm" href="{{ route('adminContacts.index') }}">X</a>
#endif
</form>
</div>
<!-- Table -->
<div class="container">
<div class="row" >
<table class="table table-hover" id="contactsTable">
<thead>
<tr>
<th>#</th>
<th>#sortablelink('name', 'Contact Name')</th>
<th>#sortablelink('number', 'Phone Number')</th>
<th>
<button class="btn btn-primary btn-sm">Prepend</button>
</th>
</tr>
</thead>
<!--Loop through all the cutomers and output them on the table-->
#foreach($contacts as $contact)
<tbody>
<tr>
<td>{{ $contact->id }}</td>
<td>{{ $contact->name }}</td>
<td>{{ $contact->number }}</td>
<td>
View
</td>
</tr>
</tbody>
#endforeach
</table>
{!! $contacts->appends(\Request::except('page'))->render() !!}
</div>
</div>
The error is:
Undefined variable: user_id (View: D:\laragon\www\SampleContacts\resources\views\adminContacts\index.blade.php)
Am I missing something? The idea is to pass the $user_id to the adminContact.create form where i can use it to set
$contact->owner_id = $user_id;
so the entered contact apears under that users table.
I don't think you can pass variables into your view like you're doing now.
In your controller, try changing this line:
return view('adminContacts.index')->withContacts($contacts)->withUserId($user_id);
To this:
return view('adminContacts.index')->with('contacts', $contacts)->with('user_id', $user_id);
You could explicitly name the variable when passing it to the view, either this way
return view('adminContacts.index')->with('user_id', $user_id);
Or
return view('adminContract.index', compact('user_id'));
I'm not sure what the name of the variable becomes when passed to the view via withUserId, but I'm guessing this is the issue.
Found the problem.
#extends('layouts.app')
#section('content')
<div class="container">
<h1 class="jumbotron">Sample Phone Book</h1>
Add Contact
</div>
<!--Search Field -->
<div class="container">
<form method="GET" action="{{ route('adminContacts.index', $user_id) }}">
<input type="text" name='filter' class='input' placeholder='Search' value="{{ request('filter') }}">
#if (request('filter'))
<a class="btn btn-primary btn-sm" href="{{ route('adminContacts.index', $user_id) }}">X</a>
#endif
</form>
</div>
<!-- Table -->
<div class="container">
<div class="row" >
<table class="table table-hover" id="contactsTable">
<thead>
<tr>
<th>#</th>
<th>#sortablelink('name', 'Contact Name')</th>
<th>#sortablelink('number', 'Phone Number')</th>
<th>
<button class="btn btn-primary btn-sm">Prepend</button>
</th>
</tr>
</thead>
<!--Loop through all the cutomers and output them on the table-->
#foreach($contacts as $contact)
<tbody>
<tr>
<td>{{ $contact->id }}</td>
<td>{{ $contact->name }}</td>
<td>{{ $contact->number }}</td>
<td>
View
</td>
</tr>
</tbody>
#endforeach
</table>
{!! $contacts->appends(\Request::except('page'))->render() !!}
</div>
</div>
#endsection
Anywhere where there is a {{ route('adminContacts.index') }} it also needed the $user_id to be passed along with it because I'm also using it in the routes as '/adminContacts/{user_id}'
Thank you for all the help.

Trying to get property of non-object on Laravel 5

Thank you for all the help in the past.
On my app, when i try to view a certain blade, it returns the error
"Trying to get property of non-object".
It has pointed me to the blade and the section of code where the error comes from:
#extends('layouts.app')
#section('content')
#component('dashboard.frame')
<div class="panel panel-default">
<div class="panel-heading">
Create
Activation Pins - {{ $item->name }}
</div>
{{--<div class="panel-body">--}}
{{--#if($pin_item && !$pin_item->pivot->is_paid )--}}
{{--<form action="/activation-pins/{{ $pin_item->id }}" method="post">--}}
{{--<input type="hidden" name="_method" value="PUT">--}}
{{--<input type="hidden" name="vendor_id" value="{{ $item->vendor->id }}">--}}
{{--{!! csrf_field() !!}--}}
{{--<button type="submit" class="btn btn-success">Mark As Paid</button>--}}
{{--</form>--}}
{{--#endif--}}
{{--</div>--}}
<table class="table">
<thead>
<tr>
<th>S/N</th>
<th>Name</th>
<th>Is Active</th>
<th>User</th>
</tr>
</thead>
<tbody>
#forelse($item->activation_pins as $itm)
<tr>
<td>{{ $loop->index + 1 }}</td>
<td>{{ $itm->pin }}</td>
<td>
<span class="label label-{{ $itm->is_active ? ( $itm->is_valid ? 'info' : 'danger' ) : 'warning' }}">
{{ $itm->is_active ? ( $itm->is_valid ? 'active' : 'expired' ) : 'inactive' }}
</span>
</td>
<td>
{{ $itm->user_id ? $itm->user->email : '-' }}
</td>
</tr>
#empty
<tr>
<td colspan="6">
<p class="text-center">No Activation Pins</p>
</td>
</tr>
#endforelse
</tbody>
</table>
</div>
#endcomponent
#endsection
With emphasis on:
<td>
{{ $itm->user_id ? $itm->user->email : '-' }}
</td>
Could I be missing something? Thanks.
This is what it displays now:

Laravel web app displaying incorrect database entries

I am trying to troubleshoot a web app that is not functioning 100% correctly that was built by a former employee. I have a novice understanding of PHP.
This is a relatively simple app that displays past exam files, but is locked down to the public. It is working correctly for the most part except for a weird thing happening with sample answer files. Not every exam has a sample answer file. The ones that don't have one should just be blank. However what is happening is that some exam files that do not have a corresponding answer file are displaying the button for exam files for other exams.
You can see from this image, that the first exam from Spring 1997 shows a blank space for sample answer which is correct. the next three exams are also correct in that they are showing the correct answer file, however, the last three exams do not actually have sample answer files in the database but are showing the sample answer for Spring 2004, like they are repeating the last file name that is in a specific sequence.
What I think is happening is that there is nothing in the code specifically saying to render a blank space if there is no corresponding answer file, but I don't know if this is actually the case. This is the code from index.blade.php:
<div class="row">
<h4>Browse past exams</h4>
<form class="form-inline">
<div class="form-group">
<label class="col-sm-2">Course</label>
<div class="col-sm-4">
{{ Form::select('course', $courses, Input::get('course', ''), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<label class="col-sm-2">Faculty</label>
<div class="col-sm-4">
{{ Form::select('faculty', $faculties, Input::get('faculty', ''), array('class' => 'form-control')) }}
</div>
</div>
<div class="form-group">
<div class="col-sm-4">
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
</div>
</div>
{{ Form::close() }}
</form>
#if(PastExamsPublicController::isAdmin())
<div class="col-md-10 col-md-offset-1" style="margin-top: 25px; margin-bottom: 25px;">
<div class="btn-group" role="group">
<a href="{{ route('past-exams.utlaw.admin.exams.create') }}" class="btn btn-primary">
Add exam
</a>
<a href="{{ route('past-exams.utlaw.admin.faculty.index') }}" class="btn btn-primary">
Manage faculty
</a>
<a href="{{ route('past-exams.utlaw.admin.course.index') }}" class="btn btn-primary">
Manage courses
</a>
</div>
</div>
#endif
<hr>
</div>
<div class="row">
<div class="col-md-10 col-md-offset-1 col-xs-12">
<table class="table table-hover" id="past-exams-table" class="sort">
<thead>
<tr>
<th class='sort-default'>Course</th>
<th>Session/year</th>
<th>Faculty</th>
<th class='no-sort'>Exam</th>
<th class='no-sort'>Sample Answers</th>
</tr>
</thead>
<tbody>
#foreach($exams as $exam)
<tr>
<td>{{ $exam->course->name }}</td>
<td data-sort="{{ $exam->year . $exam->session->name }}" >
{{ $exam->session->name . '/' . $exam->year }}
</td>
<td>{{ $exam->faculty->last_name . ', ' . $exam->faculty->first_name }}</td>
<?php
foreach($exam->files as $file) {
if($file->type == 'a') {
$answers = $file->filename;
}
else{
$examf = $file->filename;
}
}
?>
<td>
<a href="{{ asset('files/' . $examf) }}" class="btn btn-warning">
<span class="glyphicon glyphicon-download" aria-hidden="true"></span> Exam
</a>
</td>
<td>
#if(isset($answers))
<a href="{{ asset('files/' . $answers) }}" class="btn btn-primary">
<span class="glyphicon glyphicon-download" aria-hidden="true"></span> Sample Answers
</a>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
Thank you in advance for any guidance in helping point me to the genesis of the error.
Your problem exists here:
foreach($exam->files as $file) {
if($file->type == 'a') {
$answers = $file->filename;
}
else{
$examf = $file->filename;
}
}
This is contained inside a foreach loop so gets run for each exam. If the exam type is "a", the $answers variable gets set, but there is nothing that clears it if it is not set. Would recommend initializing it to null before the loop:
$answers = null;
$examf = null;
foreach($exam->files as $file) {
if($file->type == 'a') {
$answers = $file->filename;
}
else{
$examf = $file->filename;
}
}
EDIT: As pointed out by #mopo922, you will want to do the same with $examf, which I added above.

Categories