public function orderView(Request $request){
$orderByID = $request->id;
$orderDetailsView = DB::table('order_details')
->where('order_id',$orderByID)
->get();
return view('admin.order.vieworder', ['orderDetailsView' => $orderDetailsView]);
}
If i return only $orderByID it shows the id. But using this id i cannot fetch data from the database table. it shows empty array.
Try this code
$orderss = DB::table('order_details')->where('order_id', '=', $orderByID)->get();
Related
I am trying to create an API that will return all customers record from the database. But this provides pagination and filtering.,
The filtering feature is an optional query parameter. So would not necessary included it inside query parameter.
But i am facing an issues in doing that.
Here is my index methods from CustomerController file:
public function index(Request $request)
{
// Get how many item per page
$itemPerPage = $request->query('per_page');
// SQL Query
$customers = Customer::all();
// Filter data
if (!empty($request->name)) {
$customers = $customers->where('name', '=', $request->name);
}
// Return the result as JSON
return new CustomerCollection($customers->paginate($itemPerPage));
}
Or have any better approach to combine optional filtering feature with pagination?
Thank you.
Your main issue is this line:
$customers = Customer::all();
The all() method immediately returns all customers records as a Collection, which does not have a ->paginate() method: https://laravel.com/docs/9.x/collections#available-methods.
To optionally chain, use the ->query() method, or a ->when() clause:
Using ::query() instead of ::all():
$itemPerPage = $request->query('per_page');
// SQL Query
$customers = Customer::query();
// Filter data
if (!empty($request->name)) {
$customers = $customers->where('name', '=', $request->name);
}
// Return the result as JSON
return new CustomerCollection($customers->paginate($itemPerPage));
Using a ->when() clause:
$itemPerPage = $request->query('per_page');
$customers = Customer::when(!empty($request->name), function ($query) use ($request) {
$query->where('name', '=', $request->name);
});
return new CustomerCollection($customers->paginate($itemPerPage));
i want to use the result of that query and pass it into my pdfview and create a pdf based on the result. i have using sessions but did not work, is there any other solution
my controller for the search query:
public function index(Request $request){
$rsearch= $request->rsearch;
$fromdate= $request->fromdate ;
$todate= $request->todate ;
$rents = DB::table('rentcollection')
->join('tenants','rentcollection.AccountNo','=','tenants.AccountNo')
->join('propertys','tenants.PropertyID','=','propertys.PropertyID')
->select(DB::raw("CONCAT(tenants.OtherNames,' ',tenants.Surname) as
Fullname"),'rentcollection.Date as Date','rentcollection.Amount as
Amount','rentcollection.Period as Period','rentcollection.ReceiptNo as
Receipt','tenants.RegDate
as RegDate', 'tenants.AccountNo as Accno','tenants.Rent as Rent',
'tenants.NoOfProperty as
NoOfProperty','propertys.Address as Address','propertys.Property as Property')
->where('propertys.Address','like','%'.$rsearch.'%')
->whereBetween('Date', [$fromdate, $todate])
->paginate(20);
return view('reports.rent', compact('rents',));
}
my controller for creating pdf:
public function createPDF(Request $request){
$datas = $request->session()->get('cart');
$pdf = PDF::loadView('pdf.rent', ['orderedrent' => $datas,])->setPaper('A4','landscape');
return $pdf->stream('invoice.pdf');
}
I'm in a situation where I need to display the last 5 unique commenters information at the top of the comment list as follows screenshot.
comment image
To do this. I did as follows:
Post Model
public function comments()
{
return $this->hasMany(Comment::class);
}
public function commenter_avatars(){
return $this->comments()->distinct('user_id')
->select('id','post_id','user_id','parent_id')
->whereNull('parent_id')
->with('user')->limit(5);
}
My Controller method as follows
public function index() {
$feeds = auth()->user()
->posts()
->with(['user:id,first_name,last_name,username,avatar', 'media', 'commenter_avatars'])
->orderBy('id', 'desc')
->paginate(10);
return PostResource::collection($feeds);
}
I tried to use groupBy and Distinct.. But did't work as expected.
Did I miss something? or Have there any more best way to solve this?
Thank you in advance!
Noted: I am using latest Laravel (8.48ˆ)
I don't know about your joining of post, user and comments table. But i guess, you can do something similar to following.
At first get latest 5 unique user id of one post:
$userIds = Comments::where("post_id", $post_id)->distinct("user_id")->orderBy("id")
->limit(5)->pluck('user_id');
Then, fetch those user information
$users = Users::whereIn("id", $userIds )->get();
Then, you can return those users
UPDATE
You may use map() to fetch and reorder output. Following is an idea for you:
In Controller:
public function index(Request $request) {
$skipNumber = $request->input("skip"); // this is need for offsetting purpose
$userIds = [];
$feeds = Posts::with("comments")->where("comments.user_id", Auth::id())
->skip($skipNumber)->take(10)->orderBy('comments.id', 'desc')
->map(function ($item) use($userIds){
$users = [];
$count = 0;
foreach($item["comments"] as $comment) {
if(!in_array($comment["user_id"], $userIds) && $count < 5){
$count++;
$userIds.push($comment["user_id"])
$user = User::where("id", $comment["user_id"])->first();
$users.push($user);
}
if($count == 5) break;
}
$data = [
"post" => $item,
"latest_users" => $users
];
return $data;
})->get();
return PostResource::collection($feeds);
}
My code syntax may be slightly wrong. Hopefully you will get the idea.
I have solved this issue by using eloquent-eager-limit
https://github.com/staudenmeir/eloquent-eager-limit
This is my code in getting the data from the database to pass to review page. But the problem here is it will took 1min 30secs or 2-3mins before the loading will be finished.
$province = $this->getProvince(); // Get Province Library
$cityPostalCode = $this->getCityPostalCode($id = null); // Get City Library
$occupations = $this->getOccupations(); // Get Province Library
$schoolname = $this->getSchoolname(); // Get Schoolname Library
return view('pages.frontend.review', compact('data',
'province',
'cityPostalCode',
'occupation',
'schoolname')
);
This is my code in getting each data in database
For province
protected function getProvince(){
$province = Db::table('address_library')->select('province',
'province_code')->distinct()->get(); return $province;
}
For City Postal Code
protected function getCityPostalCode($id){
if(!empty($id)){
$cityPostalCode = Db::table('address_library')
->select('province_code','city','postal_code')
->where('province_code','=',$id)
->distinct('postal_code')
->get(); }
else {
$cityPostalCode = Db::table('address_library')
->select('province_code','city','postal_code')
->distinct('postal_code')
->get();
}
return $cityPostalCode;
}
For Occupations
protected function getOccupations(){
$occupation_library = Db::table('occupation_library')
->select('id', 'title')
->orderBy('id', 'ASC')
->distinct()
->get();
return $occupation_library;
}
For Schoolname
protected function getSchoolname(){
$schoolname = Db::table('schoolname_library')
->select('code', 'name')
->orderBy('id', 'ASC')
->get();
return $schoolname;
}
It will took 1min 30secs or 2mins before loading the page
If you are working with a lot of data you are better of with using chunk approach, like mentioned in the official docs.
If it's still unclear I will post an example
the question is how to get data from foreign key into my controller and pass to Session flash message view.
AbsenController#store
$this->validate($request, [
'siswa_id' => 'required',
'keterangan' => 'required',
]);
$alpaCount = Absen::where('siswa_id', '=', $request->siswa_id)
->where('keterangan', '=', 'Alpa')
->count();
if (Absen::where('siswa_id', '=', $request->siswa_id)
->whereRaw('DATE(created_at) = CURDATE()')
->exists()) {
return redirect()->back()->with('message', 'Data Telah Tersedia');
} elseif($alpaCount >= 3) {
$absen = new Absen;
$absen->siswa_id = $request->siswa_id;
$absen->keterangan = $request->keterangan;
$absen->save();
$nama = Siswa::where('id', '=', $request->siswa_id)->get();
Session::flash('warning', $nama->nama.' Sudah Lebih Dari 3 Kali
Alpa');
return redirect()->route('absen.index')
Look on $nama = Siswa::where('id', '=', $request->siswa_id)->get();
im trying to get data with $request->id and get the nama field and then pass to Session::flash('warning', $nama->nama.' Sudah Lebih Dari 3
Kali Alpa');
return redirect()->route('absen.index');
Absen#siswa
public function siswa()
{
return $this->belongsTo('App\Siswa');
}
Siswa#absen
public function absen()
{
return $this->hasMany('App\Absen');
}
maybe you can help me, Thanks
Absen Table
Siswa Table
find($request->id) i assume that $request->siswa_id because i can't find $request->id anywhere in your code
try this using Constraining Eager Loads
$nama = Absen::with(['siswa' => function ($query) use ($request) {
$query->where('id', $request->siswa_id);
}])->get();
Session::flash('warning', $nama->siswa->nama.' Sudah Lebih Dari 3
Kali Alpa');
EDIT ANSWERS
Based on table you shown in your question, it can be done like this
$namas = Absen::where('siswa',$request->siswa_id)->get(); //will return array because of absent as many siswa
foreach($namas as $nama) {
$siswa_name = $nama->siswa->nama;
}
You can load Absen with siswa, in where clause while filtering siswa_id, it binds to $request->siswa_id
$nama = Absen::with(['siswa' => function ($query) use($request) {
$query->where('siswa_id', $request->siswa_id;);
}])->get();
Also, you can lazy-eager load:
$name = Absen::find($request->id);
and then call load function to load related model.
$name->load('siswa');
Since siswa is an array. You can loop through that and find the desired object name. Or you can simply just take the first element by using first() function. e.g.
$nama->siswa->first()->anyproperty;