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'));
}
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 am using Laravel Framework 8.62.0 and PHP 7.4.20.
I get the following error:
Call to undefined method Illuminate\Database\Eloquent\Builder::links() (View: /home//Code/test_project/resources/views/index.blade.php)
I have a view that has uses 3 simple filters. To display the view via get I use the following:
public function getSearchView()
{
try {
$con = 'mysql_prod';
// search results
$items = Item::on($con)->select(['items.name AS item_name', 'items.slug', 'items.id AS item_id', 'item_details.sticker_number', 'item_details.section', 'item_details.type', 'collections.name AS collections_name', 'collections.sport_type', 'collections.league', 'collections.year as collections_year', 'images.file_name'])
->leftJoin('item_details', 'items.id', '=', 'item_details.items_id')
->leftJoin('collections', 'items.collections_id', '=', 'collections.id')
->leftJoin('images', 'images.items_id', '=', 'items.id')
->limit(500)
->paginate(10);
// filter field
$condition = Condition::on($con)->select(['id', 'name AS condition_name'])
->distinct()
->get();
$collection = Collection::on($con)->select(['id', 'name AS collection_name'])
->distinct()
->orderBy('collection_name', 'ASC')
->get();
return view('index', compact('items'));
} catch (\Exception $e) {
Log::error($e);
report($e);
}
}
To filter the view I use:
public function postFilter(Request $request)
{
try {
$con = 'mysql_prod';
//##################################
// QUERY - SEARCH RESULTS
//##################################
$items = Item::on($con)->select(['items.name AS item_name', 'items.slug', 'items.id AS item_id', 'item_details.sticker_number', 'item_details.section', 'item_details.type', 'collections.name AS collections_name', 'collections.sport_type', 'collections.league', 'collections.year as collections_year', 'images.file_name'])
->leftJoin('item_details', 'items.id', '=', 'item_details.items_id')
->leftJoin('collections', 'items.collections_id', '=', 'collections.id')
->leftJoin('images', 'images.items_id', '=', 'items.id');
// collection
if(!is_null($request->select_collection_field)) $items->where('collections.id', '=', intval($request->select_collection_field));
// FILTER field
if(!is_null($request->select_filter_field)) {
if($request->select_filter_field === "select_all") $items->orderBy('item_name', 'desc');
if($request->select_filter_field === "publishing_year") $items->orderBy('collections_year', 'desc');
}
// query database
$items->limit(500)->paginate(10);
//##################################
// FILTERS
//##################################
$condition = Condition::on($con)->select(['id', 'name AS condition_name'])
->distinct()
->get();
$collection = Collection::on($con)->select(['id', 'name AS collection_name'])
->distinct()
->orderBy('collection_name', 'ASC')
->get();
return view('index', compact('items', 'condition', 'collection'));
} catch (\Exception $e) {
Log::error($e);
report($e);
}
}
In my web.php I have the two endpoints:
Route::get('/', [SearchController::class, 'getSearchView'])->name('/');
Route::post('postFilter', [SearchController::class, 'postFilter']);
In my view I use the pagination of laravel:
{!! $items->links('vendor.pagination.default') !!}
Any suggestions why I get the above error and how to fix it?
I appreciate your replies!
$items is currently a Query Builder instance. This object wont change, it will continue to be a Query Builder instance. When you execute a query from a Query Builder you get a returned result, and that is what you need to be passing to your view. You could reassign $items to this result easily:
$items = $items->limit(500)->paginate(10);
Now $items is the Paginator instance because you reassigned that variable to the result of the paginate call.
public function boot()
{
Paginator::defaultView('view-name');
Paginator::defaultSimpleView('view-name');
}
add this code to AppServiceProvider. I hope it will work.
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