How to merge all models in laravel 9? - php

I want to show all slideshow when the images are not blank.
public function index()
{
$sliderProducts = Product::query()->select('slider')->whereNotNull('slider');
$sliderServices = Service::query()->select('slider')->whereNotNull('slider');
$slideShows = $sliderProducts->merge($sliderServices)
->union($sliderProducts)
->union($sliderServices)
->get();
return view('Home.index', compact('slideShows'));
}

$sliderProducts = Product::query()->select('slider')->whereNotNull('slider');
$sliderServices = Service::query()->select('slider')->whereNotNull('slider');
$sliderProducts and $sliderServices will both be instances of Illuminate\Database\Eloquent\Builder class
You need to fetch the collection before trying to merge them
To get the collection you can use get() on the Builder. Try
public function index()
{
$sliderProducts = Product::query()->select('slider')->whereNotNull('slider')->get();
$sliderServices = Service::query()->select('slider')->whereNotNull('slider')->get();
$slideShows = $sliderProducts->concat($sliderServices);
return view('Home.index', compact('slideShows'));
}
Or to execute a union query you can do
public function index()
{
$sliderProducts = Product::query()->select('slider')->whereNotNull('slider');
$sliderServices = Service::query()->select('slider')->whereNotNull('slider');
$slideShows = $sliderProducts
->union($sliderServices)
->get();
return view('Home.index', compact('slideShows'));
}

Related

Eager loading with parameter Laravel

What I want to do is to get all charts of accounts with extra value i.e. balance from the ledgers table with the parameter of $date, Is there any proper way to do it because I am facing N+1 query problem here.
Controller
public function get(Request $request){
$date = $request->date;
$coas = COA::where('parent_id', null)->get();
//return $coas;
$coas = $coas->map(function ($coa) use ($date) {
$coa['balance'] = $coa->balance($date);
return $coa;
});
return view('website.accounts.Trial.show', compact('coas', 'date'));
}
Model
public function balance($date){
$date = new Carbon($date);
$date= $date->addHours(23)->addMinutes(59)->addSeconds(59);
$balance = Ledger::where('c_o_a_id', $this->id)
->where('created_at' ,'<=', $date)
->orderBy('created_at', 'desc')
->orderBy('id', 'desc')
->pluck('balance')
->first();
if($balance){
return $balance;
}
return 0;
}
1. Set up a relationship between COA and Ledger
COA Model
public function ledgers()
{
return $this->hasMany(Ledger::class, 'c_o_a_id');
}
Ledger Model
public function coa()
{
return $this->belongsTo(COA::class, 'c_o_a_id');
}
2. Make you balance() function use that relationship to avoid querying N+1 times
COA Model
public function balance($date){
$date = new Carbon($date);
$date = $date->addHours(23)->addMinutes(59)->addSeconds(59);
if (!$this->relationLoaded('ledgers') $this->load('ledgers');
$balance = $this->ledgers->where('created_at' ,'<=', $date)
->sort(function ($a, $b) {
return [$b->created_at, $b->id] <=> [$a->created_at, $a->id];
})
->first()
->balance;
return $balance ?: 0;
}
Controller
$coas = COA::with('ledgers')->where('parent_id', null)->get();

Codeigniter 4 pagination on function in model

I'm currently stuck with the built-in pagination of CI4.
I try to paginate the results of a function in my model, which does not work:
My model:
<?php
namespace App\Models;
use CodeIgniter\Model;
class CategoriesModel extends Model
{
protected $table = 'categories';
protected $allowedFields = [];
protected $beforeInsert = ['beforeInsert'];
protected $beforeUpdate = ['beforeUpdate'];
//Kategorie(n) laden
public function getCategories($categoryID = null)
{
$db = \Config\Database::connect();
if (!$categoryID) {
$builder = $db->table('categories');
$query = $builder->get();
$results = $query->getResultArray();
} else {
$builder = $db->table('categories');
$query = $builder->where('categoryID', $categoryID);
$query = $builder->get();
$results = $query->getRow();
}
return $results;
}
}
In my controller, i try to paginate the results of the "getCategories"-function from the model:
<?php
namespace App\Controllers;
use App\Models\CategoriesModel;
use App\Models\PodcastsModel;
class Categories extends BaseController
{
public function index($page = 1)
{
$this->request->setLocale(session()->get('locale'));
//Helper laden
helper(['form', 'template', 'userrights']);
$data['template'] = getTemplate();
$model = new CategoriesModel;
$data['categories'] = $model->getCategories()->paginate(5, 'test', $page, 2);
$data['pager'] = $model->pager;
//Recht "13" (Benutzergruppen) prüfen
if ($data['userrights'][13] == 0) {
return redirect()->to('/admin');
}
//Views aufbauen
echo view($data['template'] . '/templates/header', $data);
echo view($data['template'] . '/backend/navigation');
echo view($data['template'] . '/templates/sidebar');
echo view($data['template'] . '/backend/categories');
echo view($data['template'] . '/templates/footer');
}
}
So the line
$data['categories'] = $model->getCategories()->paginate(5, 'test', $page, 2);
will cause the following error:
Error
Call to a member function paginate() on array
When i use
$data['categories'] = $model->paginate(5, 'test', $page, 2);
it works just fine. But it paginates ALL results from the categories table, as declared in the model.
But as i want to paginate the results from the function, depending on variables i pass to the model,
Is there a way to use the pagination class for model-functions?
You're not using the paginate library correctly. It must be used at the end of your query builder instead of a get() for example.
Your model could return the paginate object.
public function getCategories($nb_paginate, $categoryID = null)
{
$db = \Config\Database::connect();
if (!$categoryID) {
$results = $this->paginate($nb_paginate);
} else {
$results = $this->where('categoryID', $categoryID)->paginate($nb_paginate);
}
return $results;
}
And then catch it with your controller
$data['categories'] = $model->getCategories(5);
$data['pager'] = $model->pager;
You might want to give a look at the doc aswell : https://codeigniter.com/user_guide/libraries/pagination.html
No idea if this is "valid code" (i'm new to this formal CI4 models namespaces etc). But this works fine for me. Just make sure to filter your "search" in production properly for security
Controller:
$filter['search'] = $this->request->getGet('search');
$this->template->data['customers'] = $customer_model->get_customers_index($filter)->paginate(50);
$this->template->data['pager'] = $customer_model->pager;
Model:
function get_customers_index($filter)
{
if (isset($filter['search']) and $filter['search'])
{
$this->like('id_number', $filter['search']);
}
return $this;
}

Laravel: paginate collection issue

This is my code:
The Model:
public static function myWishlist(){
$id = Auth::id();
$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
return DB::table('books')->whereIn('id', $book_id)->get();
The Controller:
public function index(Request $request)
{$books = Wishlist::myWishlist()->paginate(20);
return view('wishlistCRUD.index', compact('books'))
->with('i', ($request->input('page', 1) - 1) * 5);
But instead of showing me all of the specified books, it says:
Method paginate does not exist.
I also tried this in the Model:
$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
return Book::whereIn('id',$book_id)->get();
But then it returns a collection and I dont know how to show that in my view.
You can not use paginate after getting result.
You can do it in this way:
public static function myWishlist() {
$id = Auth::id();
$book_id = Wishlist::where('user_id', $id)->pluck('book_id');
return Book::whereIn('id', $book_id);
}
public function index(Request $request) {
$books = Wishlist::myWishlist()->paginate(20);
return view('wishlistCRUD.index', compact('books'))
->with('i', ($request->input('page', 1) - 1) * 5);
}
First there is no need to use a static function eloquent already does that.
And second you could use local scopes like this:
Model:
public function scopeUserWishlist($query, $userID)
{
// Although a join would be nicer !
$book_ids = Wishlist::where('user_id', $userID)
->pluck('book_id');
return $query->whereIn('id', $book_ids);
}
Controller:
public function index(Request $request)
{
$books = Wishlist::userWishlist(Auth::id())
->paginate(20);
return view('wishlistCRUD.index')
->with('books', $books)
->with('i', ($request->input('page', 1) - 1) * 5);
}

Merge laravel 4 multiple relashionships

I have two relashionships in laravel v4.2. When I merge these two relashion into third function and then I call third function then I receive Uncought exception. Below is my code
public function following_friend() {
return $this->hasOne('Friend', 'following_id', 'id');
}
public function follower_friend() {
return $this->hasOne('Friend', 'follower_id', 'id');
}
public function mutual_friends() {
return $this->following_friend->merge($this->follower_friend);
}
public static function get_users_infomation_by_ids($login_id, $users_arr = array()) {
$users = User::where(function($sql) use($login_id, $users_arr) {
$sql->whereIn('id', $users_arr);
})
->with('mutual_friends')
->get(array('id', 'username', 'full_name', 'is_live', 'message_privacy', 'picture'));
return (!empty($users) && count($users) > 0) ? $users->toArray() : array();
}
I don't know that where is the problem in merging these two relashionships.
Try to write like below :-
public static function get_users_infomation_by_ids($login_id, $users_arr = array()) {
$users = User::with('mutual_friends')
->where(function($sql) use($login_id, $users_arr) {
$sql->whereIn('id', $users_arr);
})
->get(array('id', 'username', 'full_name', 'is_live', 'message_privacy', 'picture'));
return (!empty($users) && count($users) > 0) ? $users->toArray() : array();
}
Since I have used like this for one of my Project :-
public function getShipmentDetails($shipmentId = null) {
$response = Shipment::with('pdDetails','shipmentDocuments')
->where('id', $shipmentId)
->first();
if($response) {
return $response->toArray();
}
}
It works for me.

how to do this in Laravel 5.2

I have 2 public function in My Controller
public function index()
{
$projects = Project::personal()->get();
return view('projects.index')->withProject($projects);
}
other one is
public function show($id) {
$project = Project::find($id);
$tasks = $this->getTasks($id);
$files = $this->getFiles($id);
$comments = $this->getComments($id);
$collaborators = $this->getCollaborators($id);
return view('projects.show')->withProject($project)->withTasks($tasks)->withFiles($files)->withComments($comments)->withCollaborators($collaborators);}
I need get
$collaborators = $this->getCollaborators($id);
to My public function index() method to print collaborators in ('projects.index') view
how can do this?
Update your index function with this code, haven't tested it
public function index()
{
$projects = Project::personal()->get();
foreach($projects as $key => $project) {
$find = Project::find($project->id);
$tasks = $this->getTasks($project->id);
$files = $this->getFiles($project->id);
$comments = $this->getComments($project->id);
$collaborators = $this->getCollaborators($project->id);
$projects[$key]['collaborators'] = $collaborators;
}
return view('projects.index')->withProject($projects);
}
In ('projects.index') you will have collaborators value for each database record

Categories