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?
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 am a beginner in Laravel.
I make a function to show product list with filter.
I have a small problem with my code
I have this code:
class Product extends Model
{
use ScopeActiveTrait;
use Slugable;
public function setNameAttribute($value)
{
$this->attributes['name'] = $value;
$this->attributes['slug'] = $this->makeSlug($value);
}
protected $fillable = ['delivery_time', 'product_type', 'name', 'title', 'description', 'keywords', 'content', 'vat_id', 'main_category_id', 'enable', 'slug', 'small_description'];
protected $quarded = ['id'];
public $timestamps = false;
public function vat()
{
return $this->belongsTo('App\Models\VAT', 'vat_id');
}
public function category()
{
return $this->belongsTo('App\Models\Category', 'main_category_id');
}
public function selectedCategory()
{
return $this->hasMany('App\Models\SelectedProductCategory', 'product_id', 'id');
}
public function related()
{
return $this->belongsTo('App\Models\RelatedProduct');
}
public function features()
{
return $this->hasMany('App\Models\SelectedProductFeature');
}
public function frontImage()
{
return $this->hasMany('App\Models\UploadImage', 'file_id', 'id')->orderBy('order', 'ASC')->where('file_type', 'products');
}
}
public function getDyamicProducts(int $filterDrawer, int $filterMounting, int $filtershelfs, $categories, string $query)
{
if ($query != "") {
$query = $this->model->select('name', 'slug', 'products.id', 'small_description', 'promo_desc')
->with(['frontImage', 'selectedCategory', 'features'])
->where('title', 'like', '%' . $query . '%')
->orWhere('name', 'like', '%' . $query . '%')
->orWhere('content', 'like', '%' . $query . '%')
->active()
->orderBy('name', 'asc');
} else {
$query = $this->model->select('name', 'slug', 'products.id', 'small_description', 'promo_desc')
->with(['frontImage', 'selectedCategory', 'features'])
->whereHas('selectedCategory', function ($q) use ($categories) {
$q->whereIn('category_id', $categories);
})->active()
->orderBy('name', 'asc');
}
if ($filterDrawer != 0) {
$query->whereHas('features', function ($query, $filterDrawer) {
$query->where('key', 'number_drawers');
$query->where('description', $filterDrawer);
});
}
if ($filterMounting == 1) {
$query->whereHas('features', function ($query) {
$query->where('key', 'form-2');
$query->where('description', 1);
});
}
if ($filterMounting == 2) {
$query->whereHas('features', function ($query) {
$query->where('key', 'form-3');
$query->where('description', 1);
});
}
if ($filtershelfs != 0) {
$query->whereHas('features', function ($query, $filterDrawer) {
$query->where('key', 'number_shelves');
$query->where('description', $filterDrawer);
});
}
return $query->get();;
}
class SelectedProductFeature extends Model
{
protected $fillable = ['product_id', 'feature_id', 'description', 'key'];
protected $quarded = ['id'];
}
class SelectedProductCategory extends Model
{
protected $fillable = ['product_id', 'category_id'];
protected $quarded = ['id'];
}
Schema::create('selected_product_features', function (Blueprint $table) {
$table->id();
$table->bigInteger('product_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->bigInteger('feature_id')->unsigned();
$table->foreign('feature_id')->references('id')->on('product_features')->onDelete('cascade');
$table->string('key', 50);
$table->text('description')->nullable();;
$table->timestamps();
});
Schema::create('selected_product_categories', function (Blueprint $table) {
$table->id();
$table->bigInteger('product_id')->unsigned()->default(0);
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->bigInteger('category_id')->unsigned()->default(0);
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
When I run function: getDyamicProducts
I have error:
Too few arguments to function App\Repositories\ProductRepository::App\Repositories\{closure}(), 1 passed in /Applications/XAMPP/xamppfiles/htdocs/roelle/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php on line 988 and exactly 2 expected
This error is in: $query->whereHas('features', function ($query, $filterDrawer) {
What is wrong?
How can I repair this error?
You won't be able to pass extra arguments to the anonymous function that way, $filterDrawer will be null in that context - thus the error. Try this instead:
$query->whereHas('features', function ($query) use ($filterDrawer) {
// code
});
This is my function in controller
public function ajaxResponse (Request $request) {
if ($request->ajax()) {
$mat_id = $request->input('mat');
$cat_id = $request->input('cat');
$met_id = $request->input('met');
if ($cat_id != null) {
$products = Product::whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
})->get();
}
if ($mat_id != null) {
$products = Product::whereHas("productMaterial", function ($query) use ($mat_id) {
$query->whereIn('product_material_id', explode(',', $mat_id));
})->get();
}
if ($met_id != null) {
$products = Product::whereHas("productionMethod", function ($query) use ($met_id) {
$query->whereIn('production_method_id', explode(',', $met_id));
})->get();
}
if ($cat_id == null && $mat_id == null && $met_id == null) {
$products = Product::all();
}
$prod = view('partials.ajaxProducts', ['products' => $products])->render();
}
return response()->json(['prod' => $prod]);
}
all the record filtered according to $cat_id, $mat_id,$met_id
here categories and productMaterial have Many to many relations with product and productionMethod have one to many relations with the product
i want to filter data via ajax request in combination with all these three relationships
You can use:
public function ajaxResponse(Request $request) {
if ($request->ajax()) {
$mat_id = $request->input('mat');
$cat_id = $request->input('cat');
$met_id = $request->input('met');
$products = Products::query();
if ($cat_id != null) {
$products = $products->whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
});
}
if ($mat_id != null) {
$products = $products->whereHas("productMaterial", function ($query) use ($mat_id) {
$query->whereIn('product_material_id', explode(',', $mat_id));
});
}
if ($met_id != null) {
$products = $products->whereHas("productionMethod", function ($query) use ($met_id) {
$query->whereIn('production_method_id', explode(',', $met_id));
});
}
$products = $products->get();
$prod = view('partials.ajaxProducts', ['products' => $products])->render();
}
return response()->json(['prod' => $prod]);
}
public function ajaxResponse(Request $request){
if ($request->ajax()) {
$mat_id = $request->input('mat');
$cat_id = $request->input('cat');
$met_id = $request->input('met');
$products = Product::query();
if ($cat_id != null) {
$products->whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
})->get();
}
if ($mat_id != null) {
$products->whereHas("productMaterial", function ($query) use ($mat_id) {
$query->whereIn('product_material_id', explode(',', $mat_id));
})->get();
}
if ($met_id != null) {
$products->whereHas("productionMethod", function ($query) use ($met_id) {
$query->whereIn('production_method_id', explode(',', $met_id));
})->get();
}
$products = $products->get();
$prod = view('partials.ajaxProducts', ['products' => $products])->render();
}
return response()->json(['prod' => $prod]);
}
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');
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