Laravel: Undefined variable - laravel

im having a problem with my code.
I want to show the record of the student who login but im having an
undefined variable on my view.blade
Here's my Model
class Attendance extends Eloquent {
public function users()
{
return $this->belongsTo('User', 'id');
}
}
Here's my Controller
public function viewstudentAttendance()
{
$students = Auth::user()->id;
//load view and pass users
return View::make('student.view')
->with('attendances', $students);
}
Finally here's my view.blade
#extends('layouts.master')
#section('head')
#parent
<title>View Attendance</title>
#stop
{{ HTML::style('css/bootstrap.css'); }}
#section('content')
</ul>
#if ($students->count())
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
#foreach ($students as $students)
<tr>
<td>{{ $students->id }}</td>
<td>{{ $students->firstname }}</td>
<td>{{ $students->lastname }}</td>
#endforeach
</tr>
{{ HTML::script('js/bootstrap.js'); }}
</tbody>
</table>
#else
There are no attendance recorded yet
#endif
#stop
I think the problem is with my view or how i declare the variable? Please help? :(

public function viewstudentAttendance() {
//This code turns ID ONLY Check the website out for a code that retrieves data so you can loop it.
$students = Auth::user() - > id;
//Code that counts number of student
$studentCount = XXX(Google It)
//load view and pass users
return View::make('student.view') - > with('attendances', $students);
//Return StudentCount too
}
Inside your blade template, use :
#if ($studentCount > 10)
instead of
#if ($students->count())
Your students is returning ID, how could you "Count"
http://laravel.com/docs/4.2/eloquent
Inside your blade you kept doing if($students) bla bla, just to let you know it's attendances
->with('attendances', $students);
Attendances is the variable your blade will see, $student is the data you are pushing into attendances for blade

Related

Data for foreach loop returning empty yet there is data in the table laravel 8

i want to display a product with all its attributes in a page.i am using for each loop to display the data using a variable I have defined in the relationship.the problem is after fetching the data its unable to display the data on the browser.i havent understood where i have gone wrong..kindly assist.
the method in the controller
public function show($id)
{
$merchadisedata=Merchadise::find($id);
return view('backend.merchadise.productattributes')->with(compact('merchadisedata'));
}
the variable in the product model that defines the relationship,i have imported the productattributemodel class at the top
public function merchadiseattributes()
{
return $this->hasMany(Productattribute::class);
}
the foreach loop in the blade file that show the data
<table id="admindatatables" class="table table-bordered display nowrap" width="100%">
<thead class="thead-dark">
<tr>
<th>Product Name </th>
<th>Attribute Size</th>
<th>Attribute Stock</th>
<th>Attribute Price</th>
<th>Attribute Sku</th>
<th>Attribute Status</th>
</thead>
<tbody>
#foreach ( $merchadisedata->merchadiseattributes as $attribute)
<tr>
<td>{{ $attribute->merchads->merch_name }}</td>
<td>{{ $attribute->productattr_size}}</td>
<td>{{ $attribute->productattr_stock }}</td>
<td>{{ $attribute->productattr_price}}</td>
<td>{{ $attribute->productattr_sku }}</td>
<td>{{ $attribute->productattr_status}}</td>
</tr>
#endforeach
</tbody>
</table>
The problem what you have is that Laravel cant find the relation because the index name from your Productattribute table is not id. it is product_id.
Then you have declare in the model the new index name like that:
return $this->hasMany(Productattribute::class, 'foreign_key', 'local_key'); means:
public function merchadiseattributes()
{
return $this->hasMany(Productattribute::class, 'product_id', 'id');
}

How to display data from 2 tables in Laravel?

Restaurant Model
class Restaurant extends Model
{
use HasFactory;
public $timestamps = false;
public function menus(){
return $this->hasMany(Menu::class, 'resto_id');
}
public function restoimages(){
return $this->hasOne(RestoImage::class, 'resto_id');
}
}
RestoImage Model
class RestoImage extends Model
{
use HasFactory;
public $timestamps = false;
protected $fillable = ['image','resto_id'];
public function restaurants(){
return $this->belongsTo(Restaurant::class, 'resto_id');
}
}
View File
<div class="card mb-4">
<div class="card-body">
<table id="datatablesSimple">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Image</th>
<th>Address</th>
<th colspan="2">Operations</th>
</tr>
</thead>
<tbody>
#foreach($data as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->name}}</td>
<td>{{$item->email}}</td>
<td>{{$item->restoimages->image}}</td>
<td>{{$item->address}}</td>
<td><button>EDIT</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
RestoController
public function list(){
$data = Restaurant::with('restoimages')->get();
$restoimages = RestoImage::all();
return view('list', compact('data', 'restoimages'));
}
I have 2 tables, one is restaurants and other is resto_images. When an admin inserts new restaurant using a form. Record will be inserted in aboce 2 tables. resto_images table has column resto_id but when I tried to display image from resto_images table, it throws error (Attempt to read property "image" on null). Please correct me if I am wrong. Thanks in advance.
in your view, you can use the optional function of Laravel or check that there is real value in your relationship with a if,
<td>{{ optional($item->restoimages)->image}}</td>
or
<td>{{ $item->restoimages ? $item->restoimages->image : null }}</td>
Dont forget the img tag if you want to show the image and css attribute to resize the image.
If your images are directly in the public folder, then :
<td style="width:150px;height:100px;"> //some style to resize images
#if ($item->restoimages)
<img src="{{ asset($item->restoimages->image) }}" alt="">
#else
<p>no image</p>
#endif
</td>
But if your images are in public/folderName, then :
<td style="width:150px;height:100px;">
#if ($item->restoimages)
<img src="{{ asset('folderName/' . $item->restoimages->image) }}" alt="">
#else
<p>no image</p>
#endif
</td>

show all subjects offered by a student using laravel eloquent

I have done one-to-many relationships but when I loop through it in my view only one subject displays even when I have more than one subjects.
This is what I have done in my controller
$broadsheet = Broadsheet::with(['subject', 'session', 'term', 'student', 'classarm'])
->where('session_id', $request->sessions)
->where('term_id', $request->terms)
->where('class_arm_id', $request->classarms)
->selectRaw('sum(total) as totals, count(subject_id) as countrow, student_id, subject_id, session_id, term_id, class_arm_id, total')
->groupBy('student_id')
->orderBy('totals', 'desc')
->get();
return view('broadsheet.index')->with('broadsheet', $broadsheet);
This is the index view
#extends('layouts.app')
#section('content')
{{--#foreach($broadsheet as $subjects)
#foreach ($subjects->subject as $sub)
<th> {{ strtoupper($sub->subject->subject_name) }}</th>
#endforeach
#endforeach--}}
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
#foreach($broadsheet as $subject)
<th> {{ strtoupper($subject->subject->subject_name) }}</th>
#endforeach
<th>TOTAL</th>
<th>AVERAGE</th>
<th>POSITION</th>
</tr>
</thead>
<tbody>
#foreach($broadsheet as $result)
<tr>
<td>{{ $result->total }}</td>
<td>{{ $result->totals }}</td>
<td>{{ number_format($result->totals/$result->countrow,2) }}</td>
<td>{{ $i++ }}</td>
<td>{{ $result->exams }}</td>
<td>{{ $result->total }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
and this is my Broadsheet schema
class Broadsheet extends Model
{
use HasFactory;
protected $fillable = [
'student_id',
'subject_id',
'session_id',
'term_id',
'class_arm_id',
'subject_total',
];
public function student()
{
return $this->belongsTo(Student::class, 'student_id');
}
public function subject()
{
return $this->belongsTo(Subject::class, 'subject_id');
}
public function session()
{
return $this->belongsTo(Session::class, 'session_id');
}
public function term()
{
return $this->belongsTo(Term::class, 'term_id');
}
public function classarm()
{
return $this->belongsTo(ClassArm::class, 'class_arm_id');
}
}
I want to display students results like this
Intended result
Please, I would really need assistance to get this working as any help would be greatly appreciated.I just started learning laravel recently. I don't really know where the issue is coming from

Laravel - How to Approve all the posts of a particular Employee

Using Laravel-5.8, I have written a code for post of employees and it is working perfectly:
Controller
public function index()
{
$userEmployee = Auth::user()->employee_id;
$posts = Post::latest()->where('employee_id', $userEmployee)->get();
return view('admin.post.index', compact('posts'));
}
And it generates this view shown below. The view loads all the unapproved posts for a particular employee:
<table class="table table-bordered table-striped table-hover dataTable js-exportable">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th><i class="material-icons">visibility</i></th>
<th>Is Approved</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($posts as $key=>$post)
<tr>
<td>{{ $key + 1 }}</td>
<td>{{ str_limit($post->title,'10') }}</td>
<td>{{ $post->user->name }}</td>
<td>{{ $post->view_count }}</td>
<td>
#if($post->is_approved == true)
<span class="badge bg-blue">Approved</span>
#else
<span class="badge bg-pink">Pending</span>
#endif
</td>
<td>
#if($post->status == true)
<span class="badge bg-blue">Published</span>
#else
<span class="badge bg-pink">Pending</span>
#endif
</td>
</tr>
#endforeach
</tbody>
<form action="{{route('admin.post.approve', $post->id)}}" method="POST" enctype="multipart/form-data">
#csrf
#method('PUT')
<div>
<button type="submit" class="btn btn-primary"><i class="fas fa-arrow-right"></i> {{ trans('global.submit') }}</button>
</div>
</form>
I want to add a submit button to the view called approve. Once the button is clicked, it checks where is_approved is = 0 for the loaded employee and turns all the is_approved that relates to the employee (the loaded) data to 1.
I have written this function in the same controller, but I see that it will only work for a selected row:
public function approve($id){
$post = Post::find($id);
if ($post->is_approved == false){
$post->is_approved = true;
$post->save();
$post->user->notify(new AuthorPostApprove($post));
Toastr::success('Post Successfully Approved');
}else{
Toastr::info('Post is already Approved');
}
return redirect()->back();
}
and have this route/web.php
Route::get('posts/', 'PostController#index')->name('post.index');
Route::put('/post/{id}/approve', 'PostController#approve')->name('post.approve');
How do I re-write my Controller, view and route to achieve this?
Thank you.
try this:
public function approve($id){
$post = Post::where('employee_id', $id)
->where('is_approved', 0)
->update(['is_approved' => 1]);
if ($post){
$post->user->notify(new AuthorPostApprove($post));
Toastr::success('Post Successfully Approved');
} else {
Toastr::info('Post is already Approved');
}
return redirect()->back();
}
Ok I do something like below
All you need to do is that when user click the button then it should call for a function where that function will update all unapproved posts. So Im implementing it as below.
First I load all the unapproved post of the current logged in user . With just adding extra where clause in to your index function
Controoler for all unapproved posts
public function index()
{ //Fetching all unapproved post and passing it into view
$userEmployee = Auth::user()->employee_id;
$posts = Post::latest()->where('employee_id', $userEmployee)->where('is_approved',0)->get();
return view('admin.post.index', compact('posts'));
}
Defining the route
Define a route like below first and that route will call for the function named as approve_all_posts in PostController .
Route::post('/post/approve_all_posts', 'PostController#approve_all_posts')->name('post.approve.all');
New function for update
Then I make the function approve_all_posts () in PostController
public function approve_all_posts(){
$unapproved_post = Post::where('is_approved',0)->update(['is_approved' => 1]);
return redirect()->back();
}
Update blade file with button
Then in admin/post/index.blade.php
I add a button called approve all posts like below
Approve all unapproved posts

How to render all data in relation in laravel

I am new in this situation, I wan't to get value of "otmain_many_otline" but I don't know how to get it, I think I should put it in array cause when I use this
$list->otmain_many_otline[0]->purpose I only get first data. My problem is I don't know the syntax how to render all data?
View
<table id="example1" class="table table-bordered table-hover">
<thead>
<th>Purpose</th>
</thead>
<tbody>
#foreach($ot_list as $list)
<tr>
<td>
{{$list->otmain_many_otline[0]->purpose}}
</td>
</tr>
#endforeach
</tbody>
</table>
Model
class OTMain extends Model
{
protected $table = 'ot_main';
public function otmain_many_otline(){
return $this->hasMany('App\OTline', 'ot_main_id','id');
}
}
class OTLine extends Model
{
protected $table = 'ot_line';
public function otline_belong_otmain(){
return $this->hasOne('App\OTMain', 'ot_main_id');
}
}
Controller
$ot_list = OTMain::whereIn('created_by', $requestor_list)
->with('otmain_many_otline')
->where('ot_status', 1)
->get();
dd($ot_list);
Output:
Your otmain_many_otline relation is hasMany meaning that it will return you collection of related objects. Make sure to read official documentation on them.
If you need to get first related object then use method first(). In your case:
#foreach($ot_list as $list)
<tr>
<td>
{{ $list->otmain_many_otline->first()->purpose }}
</td>
</tr>
#endforeach
If you need to render all related objects you can also just iterate through omain_many_otline with another #foreach:
...
<td>
#foreach ($list->otmain_many_otline as $otline)
<p>{{ $otline->purpose }}</p>
#endforeach
</td>
...
You can simply do this:
#foreach($ot_list as $list)
<tr>
<td>
#foreach($list->otmain_many_otline as $ot) // foreach for $otmain_many_otline
{{$ot->purpose}} ,
#endforeach
</td>
</tr>
#endforeach

Resources