Laravel - Paginate and get() - php

With the code below, what I wanted was paginate the query I created. But, when I try to add paginate after get, it throws an error. I wanted to remain get since I want to limit to columns that was set on $fields.
What would should be the better idea to paginate this thing? or what's a good substitute for get and limit the columns?
What I tried:
->get($this->fields)->paginate($this->limit)
Part of my controller:
class PhonesController extends BaseController {
protected $limit = 5;
protected $fields = array('Phones.*','manufacturers.name as manufacturer');
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
if (Request::query("str")) {
$phones = Phone::where("model", 'LIKE', '%'. Request::query('str') . '%')
->join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id')
->get($this->fields);
} else {
$phones = Phone::join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id')
->get($this->fields);
}
return View::make('phones.index')->with('phones', $phones);
}
}

If you look at the method signature you will see that paginate receives a second argument, $columns. So your solution would be to use
->paginate($this->limit, $this->fields);
Furthermore, you can clean up your controller by changing things slightly:
public function index()
{
$query = Phones::join('manufacturers', 'manufacturers_id', '=', 'manufacturers.id');
if ( Request::query('str') ) {
$query->where('model', 'LIKE', '%'. Request::query('str') . '%')
}
$phones = $query->paginate($this->limit, $this->fields);
return view('phones.index')->with('phones', $phones);
}

class Servicios extends CI_Controller
{
public function __construct()
{
parent::__construct();
header('Content-Type: application/json');
if (!$this->lib_validaciones->validarSesion(FALSE))
{
exit(json_encode(array("satisfactorio" => FALSE, "mensaje" => "NO TIENE SESSION ACTIVA")));
}
$this->usuarioId = $this->session->userdata("usuarioId");
}
public function index()
{
exit();
}
public function getPremios()
{
$currentPage = $this->input->get("pag");
\Illuminate\Pagination\Paginator::currentPageResolver(function () use ($currentPage)
{
return $currentPage;
});
$this->load->model('Premio');
$premios = Premio::where('activo', "TRUE")
->with(['Categoria' => function($q)
{
$q->select('id', 'nombre');
}])
->with(['Imagenes' => function ($query)
{
$query->where("activo", "TRUE");
$query->select(["imagenes.id", "imagenes.descripcion",
new Illuminate\Database\Query\Expression(
"CONCAT('" . site_url(PATH_IMAGENES_UPLOAD) . "',imagenes.id,'.',imagenes.extension) as path")
]);
}])
->with(['inventario'])
->withCount(['Favoritos', 'Favoritos AS favorito_usuario' => function ($query)
{
$query->where("usuario_id", $this->usuarioId);
}])
->orderBy("nombre")
->paginate(3);
$premios->setPath(site_url(uri_string()));
$premios->setPageName("pag");
exit(json_encode(array("satisfactorio" => TRUE, "premios" => $premios->toArray())));
}
}

Related

Different views based on user table information in Laravel 7

I have a project in Laravel 7 that has a column in the user table called organ_id that has different numbers for different users (1,2,...)
Now I want to use organ_id inside my controller, which is as follows, and by using if, different information is given to each user according to the organ number.
ProductsController.php
namespace App\Http\Controllers;
use App\User;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
if (Auth::check())
{
$organ_id = Auth::user()->getId();
}
class ProductsController extends Controller
{
public function test(Request $request) {
if ($organ_id == 1) {
function orders(Request $request) {
$data = DB::table('products_1')
->orderBy('id', 'asc')
->paginate(14);
return view('products', compact('data'));
}
function posts(Request $request) {
$data = DB::table('posts')
->orderBy('id', 'asc')
->paginate(25);
return view('posts', compact('data'));
}
/*
other functions
.
.
.
*/
}
if ($organ_id == 2) {
function orders(Request $request) {
$data = DB::table('products_2')
->orderBy('id', 'asc')
->paginate(14);
return view('products', compact('data'));
}
function posts(Request $request) {
$data = DB::table('posts')
->orderBy('writer_id', 'asc')
->paginate(10);
return view('posts', compact('data'));
}
/*
other functions
.
.
.
*/
}
}
}
User.php
public function getId()
{
return $this->organ_id;
}
Since it is not possible to use if in the controller, I wrote the public function test() and put if inside this function.
Unfortunately, in this case, the browser can not find the orders function.
you can do that
$organ_id = User::where('id',auth()->user()->id)->pluck('organ_id')->first();
if ($organ_id == 1) {
//code
}

How to get only the searched data with where clause?

$data['ads'] = PostAd::where('category_id',$id)
->orwhere('district_id','LIKE','%'.$location.'%')
->orWhere('condition','LIKE','%'.$condition.'%')
->orWhere('price','>='.$min_price)
->orWhere('price','<='.$max_price)
->orWhere('fuel',$fuel)
->orWhere('anchalorpradesh',$anchal)
->orWhere('mileage',$mileage)
->orWhere('kilometers',$kilometers)
->orWhere('engine',$engine)
->get();
i want to show data whose category_id is $id. But whenever i try to search it shows me all the data in the database. Suppose i want to search data whose kilometer is 24. There is only one data whose kilometer is 24. But instead of showing that one data it shows me all the data in database.
Try something like this, adding conditional optionally based on search parameters choosen
$query = PostAd::query();
if ( isset($id) ) {
$query = $query->where('category_id',$id);
}
if ( isset($location) ) {
$query = $query->where('district_id', 'LIKE', '%' . $location . '%');
}
if ( isset($condition) ) {
$query = $query->where('condition', 'LIKE', '%' . $condition. '%');
}
$result = $query->get();
You can use the when method to conditionally add clauses to your queries depending on a value passing a “truth” test:
PostAd::query()
->when($request->get('category_id'), function ($query, $categoryId) {
$query->where('category_id', '=', $categoryId);
})
->paginate();
The closure you pass as the second argument will receive two arguments: a query builder instance that you can modify, and the value you passed as the first parameter to the when method.
You can also take this one step further and move your filtering logic to a dedicated class:
class PostAdFilters
{
protected $request;
protected $builder;
public function __construct(Request $request)
{
$this->request = $request;
}
public function apply(Builder $builder)
{
$this->builder = $builder;
foreach ($this->request->query() as $key => $value) {
// Convert something like `category_id` to `filterByCategoryId`
$methodName = 'filterBy' . Str::studly($key);
if (method_exists($this, $methodName)) {
// If the method exists, call it
call_user_func([$this, $methodName], $value);
}
}
// Return the modified query builder
return $this->builder;
}
private function filterByCategoryId($value)
{
$this->builder->where('category_id', '=', $value);
}
private function filterByKilometers($value)
{
$this->builder->where('kilometers', '=', $value);
}
// And so on...
}
class PostAd extends Model
{
public function scopeFilters(Builder $query, PostAdFilters $filters)
{
return $filters->apply($query);
}
}
You can then inject this class in your controller method, and apply it to your model:
public function search(PostAdFilters $filters)
{
return PostAd::filter($filters)->paginate();
}
This approach is based on https://laracasts.com/series/eloquent-techniques/episodes/4

Laravel output model ordered by related table column

I have this query filter which works fine to query out the result. For example, if I need to find books which have the Author name something:
Book::with('user', 'author')
->whereHas('author', function ($query) use($filters) {
$query->filter($filters);
})->paginate(30);
But the thing is if I want to order the Books by the author names. I this case nothing happens.
How can I sort books by author name?
QueryFilter looks like this:
public function __construct(Request $request) {
$this->request = $request;
$this->filterService = new FilterService();
}
public function apply(Builder $builder) {
$this->builder = $builder;
foreach ($this->filters() as $name => $value) {
if (method_exists($this, $name)) {
call_user_func_array([$this, $name], array_filter([$value]));
}
}
return $this->builder;
}
public function filters() {
return $this->filterService->removeEmptyFieldsFromRequest($this->request);
}
And the book filter looks like this:
public function date($date) {
return $this->builder->where('date', $date);
}
public function name_sort($order = 'asc') {
return $this->builder->orderBy('name', $order);
}
You can use class join statement :
$books = Book::select('author.name AS author_name, countries.*')
->with('user')
->join('author', 'author.id', '=', 'book.author_id')
->orderBy('author.name', 'ASC')
->paginate(10);

Laravel Eloquent Relationship with 3 tables

I need to get contact name using laravel Eloquent
I have table stucture below :
CallLogs Table :
id,user_id,PhoneNumber
Phone Table :
id,PhoneNumber,contact_id
contact table :
id,Name
//CallLogs Model :
public function phone()
{
return $this->hasManyThrough('\App\Models\Phone','\App\Models\Contact','id','phoneNumber','phoneNumber');
}
// phone Model :
public function contact()
{
return $this->belongsTo(Contact::class);
}
// Contact Model:
public function phones()
{
return $this->belongsTo(Phone::class, 'contact_id');
}
Join Query :
Please look with->(['phone']) in below query
$data = CallLogs::select('*')->where('call_type', '=', '1')
->when($q, function ($query) use ($q) {
return $query->where(function ($query) use ($q) {
/** #var Builder $query */
$preparedQ = '%' . $q . '%';
$num = 0;
foreach (
[
'to_call',
'from_call',
'callcost',
'created_at'
] AS $field
) {
if ($num) {
$query = $query->orWhere($field, 'LIKE', $preparedQ);
} else {
$query = $query->where($field, 'LIKE', $preparedQ);
}
$num++;
}
return $query;
});
});
//dd($data);exit;
$outgoingcalls = $this->CallLogsFilter->applyFilter($request->get('filter', []), $data);
//$outgoingcalls = $data->paginate($count, ['*'], 'page', $pageNumber);
// Here I am using getting Name
$outgoingcalls = $outgoingcalls->with(['phone'])
->sortable()
->paginate($count, ['*'], 'page', $pageNumber);
$links = $outgoingcalls->appends(Input::except('page', 'table_only'))->links();
$filter = $request->get('search');
return compact('outgoingcalls', 'links','filter');

Laravel 5 Eloquent hasMany relation returns array:1[0 => null]

I have the following classes as models:
class WorkOrder extends Model {
protected $connection = 'qcmms-epdevl';
protected $primaryKey = "workorder-id";
public $table = "PUB.pm-work-card";
public function jobs(){
return $this->hasMany('pm-work-job', 'workorder-id', 'workorder-id');
}
}
class WorkJobs extends model {
protected $connection = 'qcmms-epdevl';
protected $table = "PUB.pm-work-job";
protected $primaryKey = "workjob-id";
}
(*) There is a field "workorder-id" in this table.
WorkorderController is as follows:
class WorkorderController extends Controller {
private $repo;
public function __construct(WorkOrderRepository $repo)
{
$this->repo = $repo;
}
public function artisan()
{
$workorders = $this->repo->getArtisanRecords();
foreach ($workorders as $workorder){
$data = array($workorder->jobs);
app('debugbar')->warning($data);
}
}
}
And the WorkorderRepository is like this:
class WorkOrderRepository
{
public function __construct(WorkOrderModel $workOrderModel)
{
$this->model = $workOrderModel;
}
public function getArtisanRecords()
{
$user = \Auth::user()->getAttribute('emp-id');
return ($this->model->select(
'pm-work-card.wo-number',
'pm-work-card.wo-initial-date',
'pm-work-card.emp-id',
'pm-work-card.workorder-id',
'pm-assets.asset-no',
'pm-assets.asset-desc',
'pm-employee.emp-name',
'pm-employee.emp-surname',
'sys-code.cde-desc',
'pm-work-spares.qty-used'
)
->join('PUB.' . 'pm-assets' , function($join)
{
$join->on('pm-assets.asset-number-id', '=', 'pm-work-card.asset-number-id');
})
->leftjoin('PUB.' . 'pm-employee' , function($join2)
{
$join2->on('pm-employee.emp-id', '=', 'pm-work-card.emp-id')
;
})
->join('PUB.' . 'sys-code' , function($join3)
{
$join3->on('pm-work-card.wo-status', '=', 'sys-code.tab-cde')
->where('sys-code.tab-no', '=', 9300);
})
->leftjoin('PUB.' . 'pm-work-spares' , function($join4)
{
$join4->on('pm-work-spares.workorder-id', '=', 'pm-work-card.workorder-id')
;
})
->where('pm-work-card.emp-id', '=', $user)
->where(function($query){
$query->where('pm-work-card.wo-status', '=', 'O')
->orwhere('pm-work-card.wo-status', '=', 'S');
})
->orderBy('wo-number', 'desc')
->get());
}
The problem I have is that $data returns arrays of null while $workorders in returns all the correct data in the controller.
I need this (mobile ability) to work without renaiming fields to Laravel's spec as the app is already deployed.(Dashes is used and not underscores)
I am new to Laravel & PHP and any help will be appreciated.

Categories