How to view the data by id on laravel 5? - php

I have some problem here.
I wanna view all data sort by "kelompok".
*kelompok means group
This is the code :
Controller
public function pengelompokan()
{
$view = DB::table('tb_siswa')->where('id', $kelompok)->get();
return view('pengelompokan')
->with('view', $view);
}
Route
Route::get('kelompok', 'belajarController#kelompok');

You can use the groupBy collection method:
$view = DB::table('tb_siswa')
->where('id', $kelompok)
->get()
->groupBy('kelompok');
Edit
Based on your comments, you could do this:
Route::get('kelompok/{groupId}', 'belajarController#kelompok');
public function pengelompokan($kelompok)
{
$view = DB::table('tb_siswa')
->where('id', $kelompok)
->get()
->groupBy('kelompok');
return view('pengelompokan', compact('view'));
}

Following is the code to resolve this
public function pengelompokan()
{
$view = DB::table('tb_siswa')->where('id', $kelompok)
->groupBy('kelompok')->get();
return view('pengelompokan')->with('view');
}
You can access groupBy data using a variable $view on blade as well.

I am using Routes but you can apply it on your Controller#show
Route::get('tutorial/{id}', function($id){
$tutorial = Tutorial::findOrFail($id);
return view('tutorial.show')->with('tutorial', $tutorial);})->name('show-tutorial');
and Also Check on your show.blade.php

Related

How to add filter and pagination with Laravel Eloquent

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

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

Use Model Function In Laravel Query

How Can i resolve this problem
i want select users where it has enter the tournament and i use hasEnteredTournament Function in my User model too know that
this is User model:
public function scopeHasEnteredTournament($query){
$active = Order::all()
->where('user_id','=',$this->id)
->where('status','=',1)
->where('pack_id','=',3)
->where('expired_at','>',now())
->first();
$tournament = Tournament::all()
->where('status','=',1)
->where('start_at','<',now())
->where('end_at','>',now())
->first();
if($active && $tournament){
return true;
}
return false;
}
and this is my controller codes:
$all = User::all()
->sortByDesc('tournamentPoints')
->where('hasEnteredTournament')
->take(200);
thanks very much
Since you work with collection, you can use filter method :
https://laravel.com/docs/8.x/collections#method-filter
just use this way...
$all = User::all()
->sortByDesc('tournamentPoints')
->hasEnteredTournament()
->take(200);
for more info see here https://laravel.com/docs/8.x/eloquent#local-scopes

How to pass controller data to view in Laravel

I'd like to know how to pass my controller data to the view using Laravel.
This my Controller:
$ourput = DB::table('database')
->leftjoin('table', 'database.id', '=', 'table.id')
// ->leftjoin('table', 'table.type_id', '=', 'table.type.id')
->where('database.id', '=', $sess_id )
-
->get();
if($Data){
return redirect('view')->with('key', $value);
}else{
return FALSE;
}
}
I believe you should be trying to return a view, not a HTTP redirect response. In which case instead of this:
return redirect('driverprofile')->with('driverprofiles', $driverData);
it should read something like this
return view('driverprofile')->with('driverprofiles', $driverData);

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