Laravel Improve Getting Data From Database - php

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

Related

reject collection method is not working in laravel

I need help to fix a problem related to dealing with laravel collection methods.
I am creating a learning website that have courrse and course episode
I have used meilisearch to search in course_episode table.
$query = $request->s;
$episodes = CourseEpisode::search($query)
->get();
after getting episodes, I have used map and reject methods of collections.
$episodes->map(function ($episode) {
$course = Course::where('id', $episode->course_id)
->select('id', 'title', 'slug', 'publish_date_time', 'publishing_status')->first();
$episode->course = $course;
return $episode;
})->reject(function ($item) {
return (Carbon::createFromFormat('Y-m-d H:i:s', $item->course->publish_date_time)->gt(Carbon::now()) || $item->course->publishing_status === 'drafted');
});
I decided to reject episodes are related to courses that have publish_date_time in the future and the course that are drafted.
In map method I get course and attach that into episode.
I used dd() function in reject method. the condition returning the correct result. but reject function does not filter results.
try like this
$episodes->reject(function ($item) {
return (Carbon::createFromFormat('Y-m-d H:i:s', $item->course->publish_date_time)->gt(Carbon::now()) || $item->course->publishing_status === 'drafted');
})->map(function ($episode) {
$course = Course::where('id', $episode->course_id)
->select('id', 'title', 'slug', 'publish_date_time', 'publishing_status')->first();
$episode->course = $course;
return $episode;
});

How Can I get Latest 5 Commentors user information By Laravel Relational Eloquent eager loading

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

retrieve data with where condition laravel 5.2 into controller

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;

I cannot fetch data from using this code

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();

Uses Tabs in Blade with Same Route, Different Methods in Laravel

I'm using tabs but same controller, different methods. How to return values to different views with same route?
In /users, get value from db via BuyerSellerController#buyers method for buyer.
Route::get('users','BuyerSellerController#buyers');
In /users as well, get value from db via BuyerSellerController#sellers method for seller.
Route::get('users','BuyerSellerController#sellers');
//BuyerSellerController
public function buyers()
{
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Buyer')
->pluck('id');
$buyers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
return View::make('pages.users')->with('buyers', $buyers);
}
public function sellers()
{
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Seller')
->pluck('id');
$sellers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
return View::make('pages.users')->with('sellers', $sellers);
}
//users.blade.php
Then I got this error:
Undefined variable: sellers (View: ...)
compact saved my life! :D
public function index()
{
/* buyers */
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Buyer')
->pluck('id');
$buyers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
/* sellers */
$buyerSeller = DB::table('buyerseller')
->where('buyerseller','=','Seller')
->pluck('id');
$sellers = DB::table('users')
->where('buyerseller','=',$buyerSeller)
->get();
return View::make('pages.users', compact('buyers', 'sellers'));
}

Categories