How to display data from 2 tables in Laravel? - 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>

Related

Laravel Livewire strange table rendering behavior

I have a table component in my page that renders a list of users, and one of the columns in the table is the user's role. when I paginate through the table of users, livewire is randomly inserting a row in the table for the role, like it's somehow getting confused and including the relationship in the loop, instead of just the main model.
This is the result after paginating:
Here's what it's doing to the markup:
It only happens the first time the page is loaded and I click one of the pagination buttons. It will randomly happen on one or more pages as I paginate through the table, but once I reach the end, I can paginate through every page any number of times without seeing it again until I refresh the page.
Here is my User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, SoftDeletes, CanResetPassword, HasFactory;
protected $with = ['role'];
public function role()
{
return $this->belongsTo(Role::class);
}
}
Here's my Role model:
class Role extends Model
{
use HasFactory, SoftDeletes;
public function user()
{
return $this->hasOne(User::class);
}
}
My Livewire UserListComponent, which is a full-page component:
class UserListComponent extends Component
{
use WithPagination;
public $search;
public $roles;
public $user;
protected $paginationTheme = 'bootstrap';
protected $listeners = ['refreshUsers' => '$refresh'];
public function mount()
{
$this->search = '';
}
public function render()
{
return view('livewire.users.index', [
'users' => User::withTrashed()->search(['first_name', 'last_name'], $this->search)->paginate(5)
]);
}
public function show($id)
{
return redirect()->route('users.edit', ['user' => $id]);
}
}
My blade view:
<x-table search="true">
#slot('head')
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
#endslot
#slot('body')
#forelse($users as $user)
<x-table.row id="{{ $user->id }}" includeStatus="true" :status="$user->deleted_at">
<td>{{ $user->id }}</td>
<td>{{ $user->first_name }}</td>
<td>{{ $user->last_name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role->name }}</td>
</x-table.row>
#empty
<x-table.empty-row colSpan="6" />
#endforelse
#endslot
#slot('paginationLinks')
{{ $users->links() }}
#endslot
</x-table>
And here's the table component content:
#props(['search' => false, 'paginationLinks' => false])
<div class="table-responsive">
<div class="d-flex flex-row justify-content-between">
<div class="col-md-3"></div>
<div class="col-md-2">
#if ($search)
<input wire:model="search" placeholder="Search" type="text" class="form-control">
#endif
</div>
</div>
<table class="table">
<thead>
<tr>
{{ $head }}
</tr>
</thead>
<tbody>
{{ $body }}
</tbody>
</table>
<div class="mt-4">
#if ($paginationLinks)
{{ $paginationLinks }}
#endif
</div>
</div>
And the table row component:
#props(['includeStatus' => false, 'status' => false, 'id'])
<tr wire:key="{{ $id }}" wire:loading.class.delay="opacity-50" wire:target="search" wire:click="show({{ $id }})">
{{ $slot }}
#if ($includeStatus)
<td>
#if ($status)
<span class=" ms-2 badge bg-danger">Inactive</span>
#else
<span class="ms-2 badge bg-success">Active</span>
#endif
</td>
#endif
</tr>

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

laravel 5.2 relationship not showing

I have a Laravel 5.2 website and I am having trouble getting my relationship data to show. It was working fine before but I can't see my data. I am not getting any errors.
View
<table class="table table-striped">
<thead>
<tr>
<th>HAWB</th>
<th>Pallet Count</th>
<th>Piece Count</th>
<th>Weight</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#foreach($cfs->hawbs as $hawb)
<tr>
<td>
<a data-toggle="collapse" data-target="#{{$hawb->hawb}}">
{{$hawb->hawb}}
</a>
</td>
<td>{{$cfs->hawb->pallet_ct}}</td>
<td>{{$hawb->piece_ct}}</td>
<td>{{$hawb->weight_no}} {{$hawb->weight_type}}</td>
<td></td>
<div id="{{$hawb->hawb}}" class="collapse">
Insert more info here
</div>
</tr>
#endforeach
</tbody>
</table>
Controller
public function getCfsStep(Request $request, $step)
{
$cfs = DB::table('cfs_deliveries');
$account = Account::pluck('name', 'id')->all();
return view('cfs.step_' . $step, compact('account', 'cfsDelivery'), ['cfs' => $request->session()->get('cfs')]);
}
CFSDelivery Model
public function hawbs()
{
return $this->hasMany('App\Hawb', 'cfs_delivery_id');
}
Hawb Model
public function cfsDelivery()
{
return $this->belongsTo('App\CfsDelivery');
}
Edit
I'm now getting this error:
Undefined property: Illuminate\Database\Query\Builder::$hawbs (View: /Applications/XAMPP/xamppfiles/htdocs/dsd-cms/resources/view‌​s/cfs/step_3.blade.p‌​hp

Laravel Trying to get property of non-object when i get data

i get this error when i get section data and the problem with section result part
the book part and author part working good
when i remove section part it working with out section_name
Laravel Framework version 5.1.25 (LTS)
Trying to get property of non-object (View: C:\xampp\htdocs\lib\resources\views\libraryViewsContainer\summary.blade.php)
my Book Model
class Book extends Model
{
public function section()
{
return $this->belongsTo('App\Section','id');
}
public function author()
{
return $this->belongsToMany('App\Author','books_authors_relationship','book_id','author_id')->withTimestamps();
}
my BooksController
public function summary(){
$all_results = Book::with('section')->with('author')->get();
return view('libraryViewsContainer.summary',compact('all_results',$all_results));
}
my summary blade
<div class="container">
<h1 class="well text-center">Library Summary</h1>
<table class="table">
<tr>
<th style="width: 25%">Section Name</th>
<th style="width: 25%">Book Title</th>
<th style="width: 25%">Book Description</th>
<th style="width: 25%">Authors</th>
</tr>
#foreach($all_results as $bookModel)
<tr>
<td>
<a href="/section/{{$bookModel->section->id}}">
<span class="label label-info">{{$bookModel->section->section_name}}</span>
</a>
</td>
<td>
{{$bookModel->book_title}}
</td>
<td>
{{$bookModel->book_description}}
</td>
<?php $authors = $bookModel->author; ?>
<td>
#foreach($authors as $author)
<a href="/author/{{$author->id}}">
<span class="label label-danger">{{$author->first_name}} {{$author->last_name}}</span>
</a>
#endforeach
</td>
</tr>
#endforeach
</table>
</div>
#stop
In controller, method "with" can be written like $all_results = Book::with('section', 'author')->get();
Method compact() takes the variable names, not the variables.
return $all_results before view to see your results to get whether you're getting the values correctly or not.
the error was in Book model
i changed
public function section()
{
return $this->belongsTo('App\Section','id');
}
to
return $this->belongsTo('App\Section');
and it worked thanks for all help me

Laravel: Undefined variable

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

Resources