How i can write this query in laravel? - laravel

I need help for this query in laravel
$forums = \DB::select('SELECT * FROM forums
WHERE category = '.$f.' &&
(community = "'.$c.'" || community = "xx")
ORDER BY id ASC');
But how i can write this with laravel sytaxt?
$forums = Forums::where()

Try this way
$forums = Forum::where("category", $f)
->where(function($query) use($c) {
$query->where("community", $c)
->orWhere("community", "xx");
})
->orderBy("id", "ASC")
->get();

By default, Laravel is assuming that the database table is the plural form of the model name.
I think your Model is Forum not Forums.
Try this :
$forums = Forum::where("category", $f)
->where(function($query) use($c) {
$query->where("community", $c)
->orWhere("community", "xx");
})
->orderBy("id", "ASC")
->get();

Related

multiple search option in laravel model with join

i want to create a multiple search option but it gives me error when i try to search
this is my code by the way
Controller
$leaves = DB::table('leaves_admin')
->join('users','users.rec_id', '=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.role_name','users.avatar')
->get();
$userList = DB::table('users')->get();
// search by name
$search = request('name');
$leaves = LeaveAdmin::join('users','users.rec_id','=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.avatar')
-> where('leaves_admin.name','LIKE','%'.$search.'%')
->get();
// search by status
$search = request('status');
$leaves = LeaveAdmin::join('users','users.rec_id','=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.avatar')
-> where('leaves_admin.status','LIKE','%'.$search.'%')
->get();
return view('Leave.leaves', compact('leaves'));
As per my understanding of your code that you are looking for a solution for multiple filters and I am assuming that all columns are present in the same Query, so I will promote that solution for you.
$name = (request('name')) ? request('name') :'';
$status = (request('status')) ? request('status') :'';
$query = DB::table('leaves_admin')
->join('users','users.rec_id', '=', 'leaves_admin.rec_id')
->select('leaves_admin.*','users.role_name','users.avatar');
if(!empty($name) && !empty($status) ) {
$query->where('leaves_admin.name','LIKE','%'.$name.'%');
$query->where('leaves_admin.status','LIKE','%'.$status.'%');
}elseif (!empty($name)) {
$query->where('leaves_admin.name','LIKE','%'.$name.'%');
}elseif (!empty($status)) {
$query->where('leaves_admin.status','LIKE','%'.$status.'%');
}
$leaves = $query->get()->toArray();
return view('Leave.leaves', compact('leaves'));

How can I convert native PHP7 into query eloquent Laravel?

I'm migrating from php 7 to laravel and am having trouble completing the query. how to solve data query like the example below
$year = date('Y');
$month = date('m');
select id, tglupload,
substring(CONVERT(varchar,tglupload,106),4,2) date,
COUNT(1) as Totalemployeall
from [MS_SK]
where substring(CONVERT(varchar,tglupload,106),4,2) = $month
and substring(CONVERT(varchar,tglupload,106),7,4) = $year
AND (status_allow <> 'NOTALLOW' OR status_allow is null)
GROUP BY rollup(id, tglupload)
order by id ASC
Unfortunately you have to use a raw query for that. But you can make your query nicer using the Laravel's scope function.
For example in your model (the model related with the table [MS_SK]) you can add the following 2 scope functions:
class YourModel extends Model {
public function scopeFiltrateTglUpload($query, int $month=null, int $year=null)
{
$year = $year ?? date('Y');
$month = $month ?? date('m');
return $query->where(\DB::raw("substring(CONVERT(varchar,tglupload,106),4,2)", "=", $month))
->where(\DB::raw("substring(CONVERT(varchar,tglupload,106),7,4)", "=", $year));
}
public function scopeTheStatusIsNullOrNotAllowed($query)
{
return $query->where(function($subQuery) {
$subQuery->where('status_allow', '<>', 'NOTALLOW')
->orWhereNull('status_allow');
});
}
}
Then you can use them as per below:
$result = YourModel::selectRaw('
`id`, `tglupload`,
substring(CONVERT(varchar,tglupload,106),4,2) `date`,
COUNT(1) as `Totalemployeall`
')
->filtrateTglUpload()
->theStatusIsNullOrNotAllowed()
->groupBy(\Db::raw('rollup(id, tglupload)'))
->orderBy('id')
->get();
Please note that this is just an example to give you an idea. Then you should make it work :) Please tell me in the comment if you need any help.

Laravel select * where id =(select id )

Using Laravel eloquent how do I make a query like this:
select * from branches where user_id =(select id from users where name ='sara' )
Assuming that you have a user relationship in your Branch model you could use whereHas:
$branches = Branch::whereHas('user', function ($query) {
$query->where('name', 'sara');
})->get();
Update
If you're using v8.57.0 or above, you can now use the whereRelation() method instead:
Branch::whereRelation('user', 'name', 'sara')->get();
$id = Users::select('id')->where('name','sara')->first();
$barnches = branches::where('id',$id)->get();
Here Users and branches are models , first is using for 1 row and get for many rows
I would split it into two queries. First getting the id, then getting the list. Expecting your models to be called "User" and "Branches"
$user = User::where('name', 'sara');
$id = $user->id;
$branches = Branch::where('id', $id);
This site may help you Link
Try this.
$name = 'sara';
$results = BranchModel::whereIn("user_id", function ($query) use ($name) {
$query->select("id")
->from((new UserModel)->getTable())
->where("name", $name);
})->get();
You can use this:
$users = User::whereName("sara")->get()->pluck('id');
Branch::whereIn('user_id',$users)->get();

How to chain queries in laravel 5

I used to do something like this in code Igniter
$this->db->select('*');
$this->db->from($this::DB_TABLE);
if ($role == "manager") {
$this->db->where('is_manager',1);
}
if ($role == "staff") {
$this->db->where('is_staff',1);
}
$this->db->where('is_active', 1);
$this->db->order_by('last_name', 'asc');
$user_set = $this->db->get();
return $user_set;
How can I write a similar query like this in laravel 5. I new to laravel.
If you want to conditionally change the query parameters it's like:
$query = Model::select('*')
if ($role == "manager") {
$query = $query->where('is_manager',1);
}
if ($role == "staff") {
$query = $query->where('is_staff',1);
}
$user_set = $query->where('is_active', 1)->orderBy('last_name', 'asc')->get();
return $user_set;
But I think it would be more succinct like this (totally untested, but I think this would work):
return Model::select('*')
->where('is_manager', $role == 'manager' ? 1 : 0)
->where('is_staff', $role == 'staff' ? 1 : 0)
->where('is_active', 1)
->orderBy('last_name', 'ASC')
->get();
Yeah but we have this pretty great Eloquent ORM that didn't exist in Codeigniter.
Now it looks like:
Model::where('is_manager', 1)->where('is_active', 1)->orderBy('last_name', 'DESC')->get()
It's similar, but WAY more powerful.
Study the Eloquent docs and check out some of the basic examples in the Laracasts tutorials.

Paginate search result laravel

After some help in a previous post Laravel - Search Facility on site using Eloquent I now need to some help on paginating the result using the built in laravel pagination class.
public function search() //no parameter now
{
$q = Input::get('term');
if($q && $q != ''){
$searchTerms = explode(' ', $q);
$query = DB::table('wc_program'); // it's DB::table(), not DB::tables
if(!empty($searchTerms)){
foreach($searchTerms as $term) {
$query->where('JobRef', 'LIKE', '%'. $term .'%');
}
}
$results = $query->get();
dd($results); // for debugging purpose. Use a View here
}
}
Simply change get to paginate and provide number of items per page.
$results = $query->paginate(10);

Resources