Translate from CodeIgniter Active Record model to Laravel Eloquent - codeigniter

I am a CodeIgniter trying to adopt Laravel, however, I have been having a lot of problems understanding how to use Eloquent.
I suspect that if I could figure out how to translate some of my CodeIgniter Model methods to Laravel Eloquent I might be able to get on better. Hopefully, this will help others with the same problem.
Could anybody please rewrite the following from CodeIgniter to Eloquent:
public function get_products($product_id = NULL, $category_id = NULL, $limit = NULL)
{
$this->db->select('*, product.id AS product_id');
$this->db->from('product');
$this->db->join('product_unit', 'product.source_unit_id = product_unit.id', 'left');
$this->db->join('stock_levels', 'product.stock_level_id = stock_levels.id', 'left');
$this->db->join('categories', 'product.category_id = categories.cat_id', 'left');
if(isset($product_id)) {
$this->db->where('product.id', $product_id);
}
if(isset($category_id)) {
$this->db->where('product.category_id', $category_id);
}
if(isset($limit)) {
$this->db->limit($limit);
}
#$this->db->order_by('categories.cat_name', 'ASC');
$this->db->order_by('categories.cat_name', 'ASC');
$this->db->order_by('product.name', 'ASC');
$query = $this->db->get();
return $query->result_array();
}

Here's an approximate version of your query, there should be some things to tweak, but I hope you get the idea:
public function get_products($product_id = NULL, $category_id = NULL, $limit = NULL)
{
$query = Product::leftJoin('product_unit', 'source_unit_id', '=', 'product_unit.id')
->leftJoin('stock_levels', 'stock_level_id', '=', 'stock_levels.id')
->leftJoin('categories', 'category_id', '=', 'categories.cat_id');
if(isset($product_id)) {
$query->where('product.id', $product_id);
}
if(isset($category_id)) {
$query->where('product.category_id', $category_id);
}
if(isset($limit)) {
$query->limit($limit);
}
#$this->db->order_by('categories.cat_name', 'ASC');
$query->orderBy('categories.cat_name', 'ASC');
$query->orderBy('product.name', 'ASC');
dd( $query->toSql() ); /// this line will show you the sql generated and die // remove it to execute the query
return $query->get()->toArray();
}

Related

Call to a member function addEagerConstraints() on null, custom key in model Laravel

I'm refactoring a personal Laravel project and I got blocked in the way of improving it.
The function worked this way:
1. Get a collection from the model Thread
2. A foreach loop checks if a User voted that very thread, adding a custom key->value
3. Return the collection
What I had working up until now, was this:
ThreadController:
$threads = Thread::orderBy('created_at', 'desc')
->with('communities')
->with('author')
->withCount('replies')
->withCount('upvotes')
->withCount('downvotes')
->paginate(4);
foreach ($threads as $thread) {
if (Auth::user()) {
if (Vote::where('user_id', '=', Auth::user()->id)->where('thread_id', '=', $thread->id)->where('vote_type', '=', 1)->exists()) {
$thread->user_has_voted = 'true';
$thread->user_vote_type = 1;
} elseif (Vote::where('user_id', '=', Auth::user()->id)->where('thread_id', '=', $thread->id)->where('vote_type', '=', 0)->exists()) {
$thread->user_has_voted = 'true';
$thread->user_vote_type = 0;
} else {
$thread->user_has_voted = 'false';
}
}
}
return $threads;
What I would like to do is something like this:
Thread Model:
public function userVoteThread() {
if (Vote::where('user_id', '=', Auth::user()->id)
->where('thread_id', '=', $this->id)
->where('vote_type', '=', 1)
->exists()) {
return $this->user_vote_type = 1;
} elseif (Vote::where('user_id', '=', Auth::user()->id)
->where('thread_id', '=', $this->id)
->where('vote_type', '=', 0)
->exists()) {
return $this->user_vote_type = 0;
}
}
ThreadController:
$threads = Thread::orderBy('created_at', 'desc')
->with('communities')
->with('author')
->with('userVoteThread') <----- ADDING NEW MODEL FUNCTION
->withCount('replies')
->withCount('upvotes')
->withCount('downvotes')
->paginate(4);
After all, the closest I got was this error Call to a member function addEagerConstraints() on null, and I'm stuck trying to improve the code.
Is there a way to make that Thread model function work and use it through the collection?
Thank you very much!
PS: I hope I made myself understood, otherwise, ask me about it. Thank you :D
Firstly add relationship to the Thread model.
class Thread {
public function votes() {
return $this->hasMany(Thread::class);
}
}
Add your Eloquent Accessor to the Thread.
class Thread {
public function getUserVoteTypeAttribute() {
$this->votes
->where('user_id', Auth::user()->id ?? -1)
->first()->user_vote_type ?? null;
}
public function getUserHasVotedAttribute() {
return $this->user_vote_type !== null;
}
}
Now you can access these attributes on your model.
$thread = Thread::with('votes')->find(1);
$thread->user_vote_type;
$thread->user_has_voted;

Laravel filter of multiple variables from multiple models

Goodmorning
I'm trying to make a filter with multiple variables for example I want to filter my products on category (for example 'fruit') and then I want to filter on tag (for example 'sale') so as a result I get all my fruits that are on sale. I managed to write seperate filters in laravel for both category and tag, but if I leave them both active in my productsController they go against eachother. I think I have to write one function with if/else-statement but I don't know where to start. Can somebody help me with this please?
These are my functions in my productsController:
public function productsPerTag($id){
$tags = Tag::all();
$products = Product::with(['category','tag','photo'])->where(['tag_id','category_id'] ,'=', $id)->get();
return view('admin.products.index',compact('products','tags'));
}
public function productsPerCategory($id){
$categories = Category::all(); //om het speciefieke id op te vangen heb ik alle categories nodig
$products = Product::with(['category','tag','photo'])->where('category_id', '=', $id)->get();
return view('admin.products.index',compact('products','categories'));
}
These are my routes in web.php. I guess this will also have to change:
Route::get('admin/products/tag/{id}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');
Route::get('admin/products/category/{id}','AdminProductsController#productsPerCategory')->name('admin.productsPerCategory');
For filter both
change your URL like
Route::get('admin/products/tag/{tag_id?}/{category_id?}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');
Make your function into the controller like
public function productsPerTag($tagId = null, $categoryId = null){
$tags = Tag::all();
$categories = Category::all();
$query = Product::with(['category','tag','photo']);
if ($tagId) {
$query->where(['tag_id'] ,'=', $tagId);
}
if ($tagId) {
$query->where(['category_id'] ,'=', $categoryId);
}
$products = $query->get();
return view('admin.products.index',compact('products','tags', 'categories'));
}
You are trying to filter in your query but you pass only 1 parameter to your controller, which is not working.
1) You need to add your filters as query params in the URL, so your url will look like:
admin/products/tag/1?category_id=2
Query parameters are NOT to be put in the web.php. You use them like above when you use the URL and are optional.
2) Change your controller to accept filters:
public function productsPerTag(Request $request)
{
$categoryId = $request->input('category_id', '');
$tags = Tag::all();
$products = Product::with(['category', 'tag', 'photo'])
->where('tag_id', '=', $request->route()->parameter('id'))
->when((! empty($categoryId)), function (Builder $q) use ($categoryId) {
return $q->where('category_id', '=', $categoryId);
})
->get();
return view('admin.products.index', compact('products', 'tags'));
}
Keep in mind that while {id} is a $request->route()->parameter('id')
the query parameters are handled as $request->input('category_id') to retrieve them in controller.
Hope It will give you all you expected outcome if any modification needed let me know:
public function productList($tag_id = null , $category_id = null){
$tags = Tag::all();
$categories = Category::all();
if($tag_id && $category_id) {
$products = Product::with(['category','tag','photo'])
->where('tag_id' , $tag_id)
->where('category_id' , $category_id)
->get();
} elseif($tag_id && !$category_id) {
$products = Product::with(['category','tag','photo'])
->where('tag_id' , $tag_id)
->get();
} elseif($category_id && !$tag_id) {
$products = Product::with(['category','tag','photo'])
->where('category_id' , $category_id)
->get();
} elseif(!$category_id && !$tag_id) {
$products = Product::with(['category','tag','photo'])
->get();
}
return view('admin.products.index',compact(['products','tags','products']));
}
Route:
Route::get('admin/products/tag/{tag_id?}/{category_id?}','AdminProductsController#productsPerTag')->name('admin.productsPerTag');

How to do join table by ID as primary key in query -laravel

I want to do a function where filter based on 2 database tables. However, Im not sure how to put the join table in the query. Which means the data will be filtered from two table (user and employee tables) before returning the result to the datatable.
My filter query is
public function filterQuery(Request $request){
$age = $request->age;
$gender= $request->gender;
$query = user::query();
if(!empty($request->age)){
$query->where('age','>=',$age );
}
if(!empty($request->gender)){
$query->where('gender','<=',$gender);
}
$data = $query->get();
return datatables()->of($data)->make(true);
}
The table that I want to join in the query is from table employee (column = income and house_ownership) .and the primary key that connect both tables is IC.
If you have relationship in both model, you can use whereHas:
if(!empty($request->income) || !empty($request->house_ownership)){
$query->whereHas('employee', function($q) use ($income, house_ownership) {
if (!empty($income)) {
$q->where('income', $income);
}
if (!empty($house_ownership)) {
$q->where('house_ownership', $house_ownership);
}
});
}
...
Or you can just use join or leftjoin to filter another table:
public function filterQuery(Request $request){
$age = $request->age;
$gender= $request->gender;
$house_ownership = $request->house_ownership;
$income= $request->income;
$query = user::query();
$query->leftjoin('employee', 'employee.IC', '=', 'user.IC');
if(!empty($request->age)){
$query->where('user.age','>=',$age );
}
if(!empty($request->gender)){
$query->where('user.gender','<=',$gender);
}
if(!empty($request->income)){
$query->where('employee.income', $income);
}
if(!empty($request->house_ownership)){
$query->where('employee.house_ownership', $house_ownership);
}
$data = $query->select('user.*')->get();
return datatables()->of($data)->make(true);
}
Try This
public function filterQuery(Request $request){
$age = $request->age;
$gender= $request->gender;
if(!empty($request->age)){
$data = User::where('age','>=',$age)->get();
}
if(!empty($request->gender)){
$data = User::where('gender','<=',$gender)->get();
}
return datatables()->of($data)->make(true);
}
You can use Eloquent::when() to reduce if-else for Conditional Queries.
public function filterQuery(Request $request){
$query = user::query();
$query->select('user.*')->join('employee', 'employee.IC', '=', 'user.IC');
$data = $query
->when(request('age') != null , function ($q) {
return $query->where('user.age','>=',request('age'));
})
->when(request('gender') != null , function ($q) {
return $query->where('user.gender','<=',request('gender'));
})
->when(request('income') != null , function ($q) {
return $query->where('employee.income','<=',request('income'));
})
->when(request('house_ownership') != null , function ($q) {
return $query->where('employee.house_ownership','<=',request('house_ownership'));
})
->get();
return datatables()->of($data)->make(true);
}

How can i create a conditional check in laravel query

hi how can we implement a condition checks in laravel query builder
$flag_email =true;
$query = DB::table('customer');
if($flag_email) {
$query->where('email','=',$email);
}
if(!$flag_email) {
$query->where('mobile','=',$email);
}
$query->get();
use when method here to check condition see
$query = DB::table('customer')
->when($flag_email, function ($query,$email) {
return $query->where('email', $email);
})
->when(!$flag_email, function ($query,$email) {
return $query->where('mobile', $email);
})->get();
you can use ->when to do conditional check
$query = DB::table('customer')
->when($flag_email, function ($query, $email) {
return $query->where('email', $email);
})
->when(!$flag_email, function ($query, $email) {
return $query->where('mobile', $email);
})->get();
Ternary operator to the rescue:
$query = DB::table('customer')->where($flag_email?'email':'mobile',$email);
You can try by this way. This way will outputs your desire one. This just a way, I am not sure, this one is the proper way.
$flag_email =true;
$query = DB::table('customer');
if($flag_email)
$query = $query->where('email','=',$email);
if(!$flag_email)
$query = $query->where('mobile','=',$email);
$result= $query->get();

Laravel Database Query Builder error with table name

I'm making a "simple" api for laravel. This api has to handle with filters, pagination and sorting the result. To make this I use laravel query builder. The problem is that it's making a select without a table name, for example:
select * order by `id` asc
My code:
public function index()
{
$request = request();
$query = DB::table('customers')->newQuery();
// Orden
if (request()->has('sort')) {
// Multiorden
$sorts = explode(',', request()->sort);
foreach ($sorts as $sort) {
list($sortCol, $sortDir) = explode('|', $sort);
$query = $query->orderBy($sortCol, $sortDir);
}
} else {
$query = $query->orderBy('id', 'asc');
}
//Filtros
if ($request->exists('filter')) {
$query->where(function($q) use($request) {
$value = "%{$request->filter}%";
$q->where('name', 'like', $value)
->orWhere('address', 'like', $value);
});
}
$perPage = request()->has('per_page') ? (int) request()->per_page : null;
$pagination = $query->get()->paginate($perPage);
$pagination->appends([
'sort' => request()->sort,
'filter' => request()->filter,
'per_page' => request()->per_page
]);
return response()->json(
$pagination
);
}
Error:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error:
1096 No tables used (SQL: select * order by id asc) in file
C:\xampp\htdocs\iService\vendor\laravel\framework\src\Illuminate\Database\Connection.php
on line 664
UPDATE:
return DB::table('customers')->get();
If i use this, the api works fine, I have more apis working. The problem is that I need Query Builder to handle filters, sort, etc...
The problem was the way I instance a new query.
$query = DB::table('customers')->newQuery();
Correct:
$query = Model::query();
For my example:
$query = Customer::query();

Resources