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
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));
When i use this code in my User model
public function get_user_by_email($email) {
$data = $this->where('email', $email);
return $data->id;
}
I get this error
Property [id] does not exist on the Eloquent builder instance.
at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1602
1598▕ if ($key === 'orWhere') {
1599▕ return new HigherOrderBuilderProxy($this, $key);
1600▕ }
1601▕
➜ 1602▕ throw new Exception("Property [{$key}] does not exist on the Eloquent builder instance.");
1603▕ }
1604▕
1605▕ /**
1606▕ * Dynamically handle calls into the query instance.
1 app/Models/User.php:64
Illuminate\Database\Eloquent\Builder::__get()
2 app/Models/invite.php:21
App\Models\User::get_user_by_email()
Please help
the code should work and i have filled my database with dummy users. why cant i get my user id from the user model. I have used jetstream for this
You need to use first() on the Eloquent Builder to return the Model before you can access its attributes.
$data = $this->where('email', $email)->first();
return $data->id;
You can try in this way.
$data = Model::where('email', $email)->pluck('id');
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
I need to show only posts that are created that same day for specific user, user ID. I'm using Laravel Carbon for that but nothing happens, I don't know where the problem is. Here is my code
Here is my OptikaController with two users and Carbon:
class OptikaController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
$this->middleware('role:super', ['only'=>'show']);
}
public function delta(){
$date = new Carbon(request('date'));
$posts = Post::where('user_id', Auth::id(1))
->whereDate('created_at','=',$date)
->orderBy('created_at', 'DESC')
->paginate(30); //add {{ $posts->links() }} if paginate is enabled
$user_id = auth()->user()->id;
$user = User::find(1);
return view('delta', compact('date', $date))->with('posts', $user->posts);
}
public function centar(){
$user_id = auth()->user()->id;
$user = User::find(2);
return view('centar')->with('posts', $user->posts);
}
}
So I add Post::where('user_id', Auth::id(1)) and $user = User::find(1); to see all posts made today by that user id 1 but nothing happens.It's showing me all posts ever created and I need posts only created today or that day they are created. Any suggestions?
Your code seems to be working just fine. However, you should return $posts not $user->posts, your return line should look like this.
return view('delta', compact('date', $date))->with('posts', $posts);
Also, you could safely remove these lines unless you'll need to pass the user to your views.
$user_id = auth()->user()->id;
$user = User::find(1);
So your code should look something like this:
$date = Carbon::parse(request('date'));
$posts = Post::where('user_id', User::find(1)->id)
->whereDate('created_at', '=', $date)
->orderBy('created_at', 'DESC')
->paginate(30);
return view('delta')->with('date', $date)->with('posts', $posts);
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