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');
Related
I need a little help. I want to show how many products are published category wise. Here I am using this code to show how many products published by seller.
{{ \App\Product::where('published', 1)->where('added_by', 'seller')->get()->count() }}
Please help me regarding this issue. I had share my category and product DB table with Screenshot.
Category DB
Product DB
Here is categorycontroller
public function index(Request $request)
{
$sort_search =null;
$categories = Category::orderBy('order_level', 'desc');
if ($request->has('search')){
$sort_search = $request->search;
$categories = $categories->where('name', 'like', '%'.$sort_search.'%');
}
$categories = $categories->paginate(15);
return view('backend.product.categories.index', compact('categories', 'sort_search', products));
}
Here is ProductController
public function admin_products(Request $request)
{
//CoreComponentRepository::instantiateShopRepository();
$type = 'In House';
$col_name = null;
$query = null;
$sort_search = null;
$products = Product::where('added_by', 'admin');
if ($request->type != null){
$var = explode(",", $request->type);
$col_name = $var[0];
$query = $var[1];
$products = $products->orderBy($col_name, $query);
$sort_type = $request->type;
}
if ($request->search != null){
$products = $products
->where('name', 'like', '%'.$request->search.'%');
$sort_search = $request->search;
}
$products = $products->where('digital', 0)->orderBy('created_at', 'desc')->paginate(15);
return view('backend.product.products.index', compact('products','type', 'col_name', 'query', 'sort_search'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function seller_products(Request $request)
{
$col_name = null;
$query = null;
$seller_id = null;
$sort_search = null;
$products = Product::where('added_by', 'seller');
if ($request->has('user_id') && $request->user_id != null) {
$products = $products->where('user_id', $request->user_id);
$seller_id = $request->user_id;
}
if ($request->search != null){
$products = $products
->where('name', 'like', '%'.$request->search.'%');
$sort_search = $request->search;
}
if ($request->type != null){
$var = explode(",", $request->type);
$col_name = $var[0];
$query = $var[1];
$products = $products->orderBy($col_name, $query);
$sort_type = $request->type;
}
$products = $products->where('digital', 0)->orderBy('created_at', 'desc')->paginate(15);
$type = 'Seller';
return view('backend.product.products.index', compact('products','type', 'col_name', 'query', 'seller_id', 'sort_search'));
}
public function all_products(Request $request)
{
$col_name = null;
$query = null;
$seller_id = null;
$sort_search = null;
$products = Product::orderBy('created_at', 'desc');
if ($request->has('user_id') && $request->user_id != null) {
$products = $products->where('user_id', $request->user_id);
$seller_id = $request->user_id;
}
if ($request->search != null){
$products = $products
->where('name', 'like', '%'.$request->search.'%');
$sort_search = $request->search;
}
if ($request->type != null){
$var = explode(",", $request->type);
$col_name = $var[0];
$query = $var[1];
$products = $products->orderBy($col_name, $query);
$sort_type = $request->type;
}
$products = $products->paginate(15);
$type = 'All';
return view('backend.product.products.index', compact('products','type', 'col_name', 'query', 'seller_id', 'sort_search'));
}
Here is Category Model
class Category extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope('alphabetical', function (Builder $builder) {
$builder->orderBy('name', 'asc');
});
}
public function subCategories()
{
return $this->hasMany(SubCategory::class);
}
public function subSubCategories()
{
return $this->hasMany(SubSubCategory::class);
}
public function products()
{
return $this->hasMany(Product::class);
}
}
Here is Product Model
class Product extends Model
{
// protected $fillable = ['current_stock', 'variations', 'num_of_sale'];
protected $fillable = ['variations', 'num_of_sale'];
protected static function boot()
{
parent::boot();
static::addGlobalScope('published', function (Builder $builder) {
$builder->where('published', 1);
});
}
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function brand()
{
return $this->belongsTo(Brand::class);
}
public function stocks()
{
return $this->hasMany(ProductStock::class);
}
public function wishlists() {
return $this->hasMany(Wishlist::class);
}
public function taxes() {
return $this->hasMany(ProductTax::class);
}
public function flash_deal_product() {
return $this->hasOne(FlashDealProduct::class);
}
}
You need to use groupBy() on the category_id column. to give you and idea, you could write something like:
{{ \App\Product::selectRaw('category_id', 'count(*)')->where('published', 1)->where('added_by', 'seller')->groupBy('category_id')->get() }}
I wanted to left join Product and ProductPrice tables together, but my mentor said not to use the eloquent relationship. So here's the code he said to use:
This is a function in App\Http\Controllers\Api\ProductController.php that's using his custom left join:
public function table($dproduct, $start, $search, $sortColumn, $sort, $index, $limit)
{
$result['dproduct'] = $dproduct;
$result['data'] = array();
$result['recordsFiltered'] = 0;
$result['recordsTotal'] = 0;
$product = new Product();
$productResult = $product->getResult($search, $sortColumn, $sort, $index, $limit);
if ($productResult['Total'] > 0) {
$result["recordsFiltered"] = $productResult['Total'];
$counter = $start;
$data = array();
foreach ($productResult['Data'] as $productData) {
$counter++;
$data[] = $this->set($counter, $productData);
}
$result["recordsTotal"] = $counter;
$result["data"] = $data;
} else {
$result["error"] = $productResult['Message'];
}
return $result;
}
here's the actual ProductController(non-api):
class ProductController extends Controller
{
const PRODUCT = 'product';
public function __construct()
{
return parent::authenticate();
}
public function index()
{
$admin = $this->getAdmin();
$productView = $this->isView(ProductController::PRODUCT);
$productCreate = $this->isCreate(ProductController::PRODUCT);
$productUpdate = $this->isUpdate(ProductController::PRODUCT);
$productDelete = $this->isDelete(ProductController::PRODUCT);
if ($productView) {
return parent::setCompactView(ProductController::PRODUCT, compact(
'admin',
'productView',
'productCreate',
'productUpdate',
'productDelete'
));
} else {
return parent::setCompactView('error', compact('admin'));
}
}
}
Here's my Product Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\GlobalController;
class Product extends Model
{
protected $table = 'Product';
protected $primaryKey = 'Id';
public $incrementing = false;
const CREATED_AT = 'CreatedDate';
const UPDATED_AT = 'UpdatedDate';
public function getAll()
{
return self::where('Active', true)->get();
}
public function getById($Id)
{
return self::where('Id', $Id)->first();
}
public function getResult($search = '', $sortColumn = 0, $sort = '', $page = 0, $limit = 0)
{
if ($sortColumn == 1) {
$sortColumn = 'Description';
} else {
$sortColumn = 'Name';
}
if ($sort == '') {
$sort = 'asc';
}
$data = self::where(function ($query) use ($search) {
return $query->where('Name', 'like', '%' . $search . '%')
->orWhere('Description', 'like', '%' . $search . '%');
})
->skip(($page - 1) * 10)
->take($limit)
->orderBy($sortColumn, $sort)
->get();
$count = self::where(function ($query) use ($search) {
return $query->where('Name', 'like', '%' . $search . '%')
->orWhere('Description', 'like', '%' . $search . '%');
})->get()->count();
$result['Data'] = $data;
$result['Total'] = $count;
if ($count <= 0) {
$result['Message'] = GlobalController::TEXT_NO_DATA;
}
return $result;
}
public function getTotal()
{
return self::get()->count();
}
public function setDelete($id)
{
return self::where('Id', $id)->delete();
}
}
And here's my ProductPrice Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\GlobalController;
class ProductPrice extends Model
{
protected $table = 'ProductPrice';
protected $primaryKey = 'Id';
}
ProductPrice doesn't have a controller yet as i don't really understand what to type in it.
The Product table has these as tables:
Schema::create('Product', function (Blueprint $table) {
$table->uuid('Id')->primary();
$table->uuid('CategoryId')->nullable();
$table->string('Name', 60)->charset('utf8');
$table->mediumText('Description')->charset('utf8')->nullable();
$table->uuid('CreatedId')->nullable();
$table->timestamp('CreatedDate')->useCurrent();
$table->uuid('UpdatedId')->nullable();
$table->timestamp('UpdatedDate')->useCurrent();
});
Schema::table('Product', function ($table) {
$table->foreign('CategoryId')->references('Id')->on('Category')->onDelete('set null');
$table->foreign('CreatedId')->references('Uid')->on('Admin')->onDelete('set null');
$table->foreign('UpdatedId')->references('Uid')->on('Admin')->onDelete('set null');
});
and ProductPrice is this:
Schema::create('ProductPrice', function (Blueprint $table) {
$table->uuid('Id')->primary();
$table->uuid('ProductId');
$table->integer('Price')->default(0);
$table->integer('CutPrice')->default(0);
$table->integer('SpecialPrice')->default(0);
$table->smallInteger('Discount')->default(0);
$table->uuid('CreatedId')->nullable();
$table->timestamp('CreatedDate')->useCurrent();
$table->uuid('UpdatedId')->nullable();
$table->timestamp('UpdatedDate')->useCurrent();
});
Schema::table('ProductPrice', function ($table) {
$table->foreign('ProductId')->references('Id')->on('Product')->onDelete('cascade');
$table->foreign('CreatedId')->references('Uid')->on('Admin')->onDelete('set null');
$table->foreign('UpdatedId')->references('Uid')->on('Admin')->onDelete('set null');
});
My question is, what do i need to do to left join them together on ProductId as foreign key then show them in my view on the same table view?
Actually i want to search those question which user want to search after select any subject or course.
if a remove either whereHas from subject or course its works but with both its not working.
Please give a better solution for searching in belongsToMany realtionship.
i have a question table with Question model class
class Question extends Model{
public function courses(){
return $this->belongsToMany('App\Models\Course','course_questions');
}
public function subjects(){
return $this->belongsToMany('App\Models\Subject','subject_questions');
}
}
and in my searchController
public function index(Request $request){
$questions = Question::with(['user','courses','branches','subjects','years','universities','question_type'])
->where("status","=",1)
->where(function($query) use($request){
$q = $request->q;
if(isset($q) && !is_null($q)){
$query->where("question","LIKE","%$q%");
}
})
->whereHas('subjects',function($query) use($request){
$subjects = $request->subject;
if(isset($subjects)){
$_subjects = explode(" ",$subjects);
$query->whereIn("slug",$_subjects)
->orWhereIn("subject_name",$_subjects);
}
})
->whereHas('courses',function($query) use($request){
$course = $request->course;
if(isset($course)){
$_course = explode(" ",$course);
$query->whereIn("slug",$_course)
->orWhereIn("course",$_course);
}
})
->paginate();
if($request->ajax()){
$returnHTML = view('questions.question_list')->with('questions', $questions)->render();
return response()->json(array('success' => true, 'pageContent'=>$returnHTML));
}
You should build your query probably this way - you should verify conditions before adding any constraints to your query:
$query = Question::with(['user','courses','branches','subjects','years','universities','question_type'])
->where("status","=",1);
$q = $request->q;
if(isset($q) && !is_null($q)) {
$query = $query->where("question","LIKE","%$q%");
}
$subjects = $request->subject;
if (isset($subjects)) {
$query = $query->whereHas('subjects',function($query) use($subjects){
$_subjects = explode(" ",$subjects);
$query->whereIn("slug",$_subjects)
->orWhereIn("subject_name",$_subjects);
});
}
$course = $request->course;
if (isset($course)) {
$query = $query->whereHas('courses',function($query) use($course ){
$_course = explode(" ",$course);
$query->whereIn("slug",$_course)
->orWhereIn("course",$_course);
});
}
$questions = $query->paginate();
$products = Product::query()->
WhereHas('categories', function ($q) use ($keyword) {
$q->where('products.name', $keyword)
->orWhere('categories.name', $keyword);
})->get();
This is how I have used in my project
i would like to create simple ability for my users to search database table as an optional items, for example search by name or mobile or email. to create this ability i'm created this simple controller:
class SearchTransactionController extends Controller
{
public function search(Request $request)
{
$query = BuyCard::select('*');
foreach ($request->only(['name', 'mobile', 'email']) as $key => $value) {
if (strlen($value) > 0) {
$query->where($key, 'LIKE', "%$value%");
}
}
$query->orderBy('id', 'DESC');
$data = $query->paginate(15);
return view('report_buycard_transactions.index')
->with('info', $data);
}
}
all name,mobile,email is optional for search but my code dont correct search in database and return all columns
it's because adding multiple ->where() calls mean it attempts to find only rows where the search string is in all 3 of those columns, try doing this:
class SearchTransactionController extends Controller
{
public function search(Request $request)
{
$query = BuyCard::select('*');
$first = true;
foreach ($request->only(['name', 'mobile', 'email']) as $key => $value) {
if (strlen($value) > 0) {
if($first){
$query->where($key, 'LIKE', "%$value%");
$first = false;
} else {
$query->orwhere($key, 'LIKE', "%$value%");
}
}
}
$query->orderBy('id', 'DESC');
$data = $query->paginate(15);
return view('report_buycard_transactions.index')
->with('info', $data);
}
}
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())));
}
}