I have make category model and product model .
The relationship :
Category has many product
Product belongs to category
My Category.php
public function product()
{
return $this->hasMany('App\Product');
}
my Product.php
public function category()
{
return $this->belongsTo('App\Category');
}
My routes :
Route::get('categories/{id}','ShopController#items');
My ShopController#items
public function items($id)
{
$products = Product::find($id);
$categories = Category::find($id);
return view('shop.togo',compact('products','categories'));
}
In my togo.blade.php
#extends('app')
#section('content')
<div class="container">
<table class="table">
<thead>
<tr>
<th>Products belongs to {{$categories->name}}</th>
</tr>
</thead>
<tbody>
#foreach($products as $product)
<tr>
<td>{{$product->name}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#stop
How to list out the products under the specific categories? if the categories id were 1 , if i pass the value localhost:8000/categories/1 , how to show the products that has foreign key(categories_id) that belong the specific categories?
Any feedback really appreciated
Because you have a hasMany relationship you have to iterate inside an iteration like :
#foreach($products as $product)
<tr>
<td>{{$product->name}}</td>
</tr>
#foreach($product->category as $category)
{{$category->name}}
#endforech
#endforeach
Related
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>
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
First time working with eloquent relationship. I'm trying to access the subcategory method yet I get this error:
Property [subcategory] does not exist on this collection instance.
New to laravel so any help would be appreciated!
blade
<table class="table">
<thead>
<tr>
<th scope="col">Category</th>
<th scope="col">Sub-category</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $cat)
<tr>
<td scope="row">{{$cat->name}}</td>
//error here
#foreach ($categories->subcategory as $item)
<td>{{$item->name}}</td>
#endforeach
</tr>
#endforeach
</tbody>
</table>
category model
class Category extends Model
{
protected $fillable = ([
'name'
]);
public function subcategory(Type $var = null)
{
# code...
return $this->hasMany(Subcategory::class,'category_id','id');
}
}
subcategory model
class Subcategory extends Model
{
protected $fillable = ([
'category_id',
'name'
]);
public function category(Type $var = null)
{
# code...
return $this->belongsTo(Category::class);
}
}
controller
public function create()
{
$categories = Category::all();
// dd($categories);
return view('settings.create', compact('categories'));
}
You are doing wrong in foreach loop. Your second foreach loop will be like
#foreach ($categories as $cat)
<tr>
<td scope="row">{{$cat->name}}</td>
#foreach ($cat->subcategory as $item)
<td>{{$item->name}}</td>
#endforeach
</tr>
#endforeach
your current object is $cat and $categories is a collection.
You are calling subcategory of $categories collection not on one model $cat. So change your #foreach method to
#foreach ($cat->subcategory as $item)
<td>{{$item->name}}</td>
#endforeach
My solution:
#foreach ($cat->subcategory as $item)
<td>{{$item->name}}</td>
#endforeach
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
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