I want to join two tables in laravel 5.3 and fetched the value in template page .now i caught error.I have two table names as users and department.$queries = DB::getQueryLog(); return the query what I want exactly as select users.*, department.name as dept_name from users inner join department on users.department_id = department.id for the following query.this will return the error
ErrorException in Macroable.php line 74:
Method links does not exist. (View: C:\wamp64\www\testLaravel\TestTravel\resources\views\approval_view.blade.php)
BadMethodCallException in Macroable.php line 74:
Method links does not exist.
controller
class travelApprovalController extends Controller {
public function index(){
//$users = DB::table('passenger')->paginate(2);
$users = DB::table('users')
->join('department', 'users.department_id', '=', 'department.id')
->select('users.*', 'department.name as dept_name')
->get(); //->paginate(2)
return view('approval_view',['users'=>$users]);
}
approval.blade.php
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td><a href="#" class="viewPopLink" role="button" data-id="{{ $user->id }}" data-toggle="modal" data-target="#myModal">{{ $user->dept_name }}<a></td>
<td>{{ $user->dept_name }}</td>
<td>{{ $user->name }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
{{$users->links()}}
try this
$users = DB::table('users')
->join('department', 'users.department_id', '=', 'department.id')
->select('users.*', 'department.name as dept_name')
->paginate(2);
Use like this
#foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td><a href="#" class="viewPopLink" role="button" data-id="{{ $user->id }}" data-toggle="modal" data-target="#myModal">{{ $user->dept_name }}<a></td>
<td>{{ $user->dept_name }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->links }}</td>
</tr>
#endforeach
OR
{{$users[0]->links()}}
Related
Am still pretty new to laravel but there's some very weird issue am facing.
In the Laravel blade view file. It take some crazy amount of seconds to load content to the browser using Foreach method
This is from the admin section controller
$rates = Rate::where('user_id', $user->user_id)
->orderBy('id', 'ASC')
->paginate(100);
return view('admin.users-view', compact('headers', 'rates'));
The query takes about 2sec or less
On the Blade file, the foreach takes about 18sec to display this to the browser and gives me a crazy headache. Please may I know what am doing wrong?
#foreach ($rates as $rate)
<td>{{ data('days', $rate->lead_time) }}</td>
<td>{{ data('kg', $rate->weight) }}</td>
<td>{{ data('format', $rate->dropoff) }}</td>
<td>{{ $rate->tax }}</td>
<td>{{ date("d M Y", strtotime($rate->created_at)) }}</td>
<td>
<a onclick="fetchRate(this)" id="{{ $rate->id }}"
class="edit link"
content="{{ json_encode($rate) }}">
{{ Get_Lang('update', Get_Lang_Cookie()) }}
</a>
</td>
<td>
<a onclick="deleteRate(this)"
id="{{ $rate->id }}" class="edit link">
{{ Get_Lang('delete', Get_Lang_Cookie()) }}
</a>
</td>
</tr>
#endforeach
Rate Table Structure
Schema::create('rates', function (Blueprint $table) {
$table->id();
$table->bigInteger('user_id')->index();
$table->string('origin', 5);
$table->string('destination', 5);
$table->string('lead_time')->nullable();
$table->string('weight');
$table->string('dropoff')->default(0); //price amount
$table->string('tax')->default(0);
$table->timestamp('created_at', 0)->nullable()->index();
$table->timestamp('updated_at', 0)->nullable();
});
When I'm going to add data an error appears "Call to a member function count() on null"
View
#foreach ($data as $row)
<tr>
<td>{{ $row->customer}}</td>
<td>{{ $row->vessel}}</td>
<td>{{ $row->scopejob}}</td>
<td>{{ $row->pergantian_sparepart}}</td>
<td>{{ $row->teknisi}}</td>
<td>{{ $row->tahun}}</td>
<td>{{ $row->keterangan}}</td>
<td>{{ $row->images->count()}}</td>
<td>{{ $row->files->count()}}</td>
<td>
FOTO
FILE
EDIT
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
</td>
</tr>
#endforeach
Controller rekap:
public function insert_rekap(Request $request) {
// dd($request->all());
$this -> validate($request,[
'customer'=>'required',
'vessel'=>'required',
'scopejob'=>'required',
'pergantian_sparepart'=>'required',
'teknisi'=>'required',
'tahun'=>'required',
'keterangan'=>'required'
]);
$data = rekap::create($request->all());
if($request->hasFile("images")){
$images=$request->file("images");
foreach($images as $image){
$imageName=time().'_'.$image->getClientOriginalName();
$request['rekap_id']=$data->id;
$request['image']=$imageName;
$image->move(public_path("/images_rekap"),$imageName);
Image_rekap::create($request->all());
}if($request->hasFile("files")){
$files=$request->file("files");
foreach($files as $file){
$fileName=time().'_'.$file->getClientOriginalName();
$request['rekap_file_id']=$data->id;
$request['file']=$fileName;
$file->move(\public_path("/rekap_file"),$fileName);
file_rekap::create($request->all());
}
}
}
return redirect()->route('rekap')->with('success','Data Berhasil Ditambahkan');
}
but the data is successfully entered into the database, and what steps should I take to correct the error
error tells you that images or files or both variables are null, looks like you don't use eager loading
quick and dirty way is to use optional helper
<td>{{ optional($row->images)->count()}}</td>
<td>{{ optional($row->files)->count()}}</td>
if you need only count then better approach is to use eloquent counting related models
// controller
$data = rekap::withCount(['images', 'files'])
// other selecting rules
//->where ...
->get();
return view('view_name', ['data'=>$data]);
now in every $row of $data you have fields images_count and files_count
<td>{{ $row->images_count }}</td>
<td>{{ $row->files_count }}</td>
also you can rename count variables like rekap::withCount(['images as imagesCount', 'files as filesCount'])
<td>{{ $row->imagesCount }}</td>
<td>{{ $row->filesCount }}</td>
Try
<td>{{ $row->images ? $row->images->count() : '' }}</td>
Undefined variable: blogcat (View: /home/techpriest/joseph/resources/views/admin/view_category.blade.php) this is my error message in laravel 8 but when I look at my code all seems well.
here is my code.
AdminController
public function addBlogCat (Request $request){
if ($request->isMethod('post')) {
$data = $request->all();
$blogcat = new Foliocategories;
$blogcat->name = $data['category_name'];
$blogcat->save();
return redirect ('/blog/categories');
}
return view ('admin.view_category');
}
public function viewBlogCat (){
$blogcat = DB::select('select * from foliocategories');
return view ('admin.view_category', ['blogcat'=>$blogcat]);
}
And here is my view;
#foreach($blogcat as $blogcat)
<tr>
<td>{{ $blogcat->id }}</td>
<td>{{ $blogcat->name }}</td>
<td>{{ $blogcat->created_at }}</td>
<td><span class="badge badge-danger">Due</span></td>
<td class="action h4">
<div class="table-action-buttons">
<a class="edit button button-box button-xs button-info" href="#"><i class="zmdi zmdi-edit"></i></a>
<a class="delete button button-box button-xs button-danger" href="#"><i class="zmdi zmdi-delete"></i></a>
</div>
</td>
</tr>
#endforeach
I found two issues here. In the addBlogCat action, you don't inject any blog category. The viewBlogCat is not bad, but in the view, you are using a loop with a model instance.
What about rewrite the code to this, lets use full meaningful variable names:
public function addBlogCategory(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
Foliocategories::create(['name' => $request->input('category_name')]);
return redirect ('/blog/categories');
}
return view ('admin.view_category', [
'blogCatogories' => Foliocategories::all();
]);
}
public function viewBlogCategories()
{
$blogCategories = Foliocategories::all();
return view ('admin.view_category', compact('blogCategories'));
}
Then in the view:
#foreach($blogCategories as $blogCategory)
<tr>
<td>{{ $blogCategory->id }}</td>
<td>{{ $blogCategory->name }}</td>
<td>{{ $blogCategory->created_at }}</td>
</tr>
#endforeach
I really don't know how to put it. I have two tables Order.php and Product.php, a return $this->hasMany(Product::class, 'id'); in Order.php and return $this->belongsTo(Order::class, 'product_id'); in Product.php.
In my OrderController
public function index()
{
$orders = Order::latest()->paginate(10);
return view('admin.order.order')->with([
'orders' => $orders,
]);
}
in my view
#foreach($orders as $order)
<tr data-href="{{ route('orders.view', $order->id) }}">
<td></td>
<td>{{ $order->products[0]->product_name }}</td>
<td>{{ $order->order_quantity }}</td>
<td>{{ $order->customer_name }}</td>
<td>{{ $order->customer_tel_no }}</td>
<td width="300">{{ $order->customer_address }} Lorem ipsum dolor sit amet, consectetur adipisicing elit.</td>
<td>{{ $order->total_amount }}</td>
<td>
<span class="badge text-white badge-lg bg-{{ $order->is_delivered == false ? 'warning' : 'success' }}">
{{ $order->is_delivered == false ? 'Not yet delivered!' : 'Delivered!' }}
</span>
</td>
<td>{{ $order->created_at->diffForHumans() }}</td>
</tr>
#endforeach
Everything works fine until, when I have more than 15 records in the orders table I get an error Undefined array key 0
And please I'm also new to Laravel thanks
I would think this happens because of the line:
<td>{{ $order->products[0]->product_name }}</td>
Are you sure you have a product for every order?
This error would be because an $order does not have any products, therefore would have no array key 0
You can make use use php's new optional syntax while chaining which is ?-> https://stitcher.io/blog/php-8-nullsafe-operator
$order->products?->first()->product_name which should return null, if there aren't any products on this particular $order (assuming you are using php 8!)
If you are on an older version of php you should consider
#if(count($order->products))
<td>{{ $order->products[0]->product_name }}</td>
#endif
Yet another approach would be, to use laravel's optional() helper like below
<td>{{ optional($order->products)->first()->product_name }} </td>
Compare two different columns from two different tables with if statement and show other column's data from either table in laravel 5.2
controller like:
public function labDetails(){
$users = DB::table('users')->lists('lab_name');
$labdetails = Labdetails2::paginate(20);
return View('labdetails')
->with('users', $users)
->with('labdetails', $labdetails);
}
here i want to match users table's 'lab_name' column with labdetails2 table's 'lab_name' column and if they matched show only the related data from labdetails table.
N.B. I am working with an old database where there's no relationship among tables.
views like:
<form action="" method="">
<select name="state" onchange="getValue(this)">
<option value="">Select Lab</option>
#foreach ($users as $key => $user)
<option value="{{ $user }}">{{ $user }}</option>
#endforeach
</select>
<input type="submit" value="Submit">
#foreach ($labdetails as $labdetail)
<tbody>
<tr>
<td>{{ $labdetail->sl }}</td>
<td>{{ $labdetail->lab_name }}</td>
<td>{{ $labdetail->pc_name }}</td>
<td>{{ $labdetail->pc_ip }}</td>
<td>{{ $labdetail->mac1 }}</td>
<td>{{ $labdetail->assetno }}</td>
<td>{{ $labdetail->pc_type }}</td>
<td>{{ $labdetail->processor }}</td>
<td>{{ $labdetail->motherboard }}</td>
<td>{{ $labdetail->ram }}</td>
<td>{{ $labdetail->hdd }}</td>
<td>{{ $labdetail->location }}</td>
<td>{{ $labdetail->department }}</td>
<td>{{ $labdetail->entrydate }}</td>
<td>{{ $labdetail->comment }}</td>
</tr>
</tbody>
#endforeach
Please help me what should I do with the controller & views...
You can retrieve only the matches record this way
$users = DB::table('users')->lists('lab_name'); // this retrieves all lab_name as array.
Then, to retrieve only the matches labdetails
$labdetails = Labdetails2::whereIn('lab_name',$users)->paginate(20);
DB::table('users')
->join('labdetails2', 'users.lab_name', '=', 'labdetails2.lab_name')
->select('labdetails2.lab_name', 'labdetails2.pc_name')
->get()
in select(), white down the fields you required.
Here, labdetails2 and users are the table name.
this code finally worked for me:
public function showLabDetails(Request $request){
$q = $request -> request -> all();
$labdetails = Labdetails2::whereIn('lab_name', $q)->get();
return View('showlabdetails')
->with('labdetails', $labdetails);
}
thanks to everyone for helping me.