i have default laravel notifications data field and default notification table
only try to select some notification for user based on his notification data value i jhave created this function in User Model
public function notifications_data($col)
{
$notifications = $this->notifications()->where('data' , function ($q) use ($col){
$q->where('appointment_id','0'); // query data as table
})->get();
return ($notifications);
}
i have saved value in notification table col data { "type":"Appointment", "appointment_id":"0", "date":null, "updated_by":"","status":"0" }
How do i get this to get all notifications with status = 0 or appointment_id = 0
You can also use:
public function notifications_data($col)
{
$notifications = $this->notifications()
->where('data->appointment_id', 0)
->orWhere('data->status', 0)
->get();
return ($notifications);
}
Maybe this works:
public function notifications_data($col)
{
$notifications = $this->notifications()
->where('data','LIKE','%"appointment_id":"0"%')
->orWhere('data','LIKE','%"status":"0"%')
->get();
return ($notifications);
}
Using Laravel's query builder:
public function notifications_data()
{
$notifications = DB::table('notifications') //Specify the table you want to query
->where('status',0) //Where status = 0
->orWhere('appointment_id',0) //or appointment_id = 0
->get();
return $notifications;
}
public function notifications_data($col)
{
$notifications = $this->notifications()
->whereJsonContains('data->appointment_id',0)
->orWhere('data','LIKE','%"status":"0"%')
->get();
return ($notifications);
}
you can use whereJsonContains for it, you can checkout Laravel documentation https://laravel.com/docs/9.x/queries#json-where-clauses
Related
How can I make this query in Laravel eloquent. Please, no DB Record solution.
SELECT slo.batch,
slo.type,
(SELECT Count(sl1.id)
FROM sync_log sl1
WHERE sl1.status = 1
AND sl1.batch = slo.batch) AS success,
(SELECT Count(sl2.id)
FROM sync_log sl2
WHERE sl2.status = 0
AND sl2.batch = slo.batch) AS failed,
slo.created_at
FROM sync_log slo
GROUP BY batch
ORDER BY slo.created_at
Below is the database table.
Try something like :
$result=DB::table('sync_log as slo')
->select('slo.batch','slo.type', 'slo.created_at', DB::raw(('SELECT Count(sl1.id) FROM sync_log sl1 WHERE sl1.status=1 AND sl1.batch = slo.batch) AS success'), DB::raw(('SELECT Count(sl2.id) FROM sync_log sl2 WHERE sl2.status = 0 AND sl2.batch = slo.batch) AS failed')
->groupBy('batch')
->orderBy('slo.created_at')
->get();
Without any idea on your structure or models. guessing a manyToMany relation wetween batch and type where sync_log is the pivot table between them.
$batchs = Batch::withCount([
'types as success' => function ($query) {
$query->where('status', 1);
},
'types as failed' => function ($query) {
$query->where('status', 0);
}])
->get();
Using Eloquent ORM it can be tricky but I guess will work, you can define hasMany relation(s) in same model which will relate to same model using batch attribute/key like
class SyncLog extends Model
{
public function success_batches()
{
return $this->hasMany(SyncLog::class, 'batch', 'batch')->where('status',1);
}
public function failed_batches()
{
return $this->hasMany(SyncLog::class, 'batch', 'batch')->where('status',0);
}
}
Then using your model you can get count for these relations using withCount
$bacthes = SyncLog::withCount(['success_batches','failed_batches'])
->select(['batch','type'])
->distinct()
->orderBy('created_at')
->get();
If you don't want to define it twice based on where clause then you can follow the approach explained in #N69S's answer like
class SyncLog extends Model
{
public function batches()
{
return $this->hasMany(SyncLog::class, 'batch', 'batch');
}
}
$bacthes = SyncLog::withCount([
'batches as success' => function ($query) {
$query->where('status', 1);
},
'batches as failed' => function ($query) {
$query->where('status', 0);
}])
->select(['batch','type'])
->distinct()
->orderBy('created_at')
->get();
So i want to fetch data from two tables.
But i got this error :
Here is my Query from Model:
public function tampil_edit($id) {
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
return $this->db->get_where('tb_m_notaris', $id);
}
Here is my Controller :
public function tampiledit($id) {
$id = ['id' => $id];
$title['title'] = 'Notaris | Edit';
$data['notaris'] = $this->m_notaris->tampil_edit($id)->result();
$this->load->view('template/headercss',$title);
$this->load->view('template/sidebar');
$this->load->view('template/navbar');
$this->load->view('master_data/notaris/edit', $data);
$this->load->view('template/footerjs');
}
Here Is what the $id contain:
Check your SQL
WHERE id = 45
^^
This id belongs to which table? I notice there are multiple table (tb_m_notaris,tb_m_user) with id column.
To call function
tampil_edit(45) {} # makesure $id is not an array
In model
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->from('tb_m_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id = tb_m_notaris.id');
$this->db->where('tb_m_notaris.id', $id);
return $this->db->get()->result();
}
You should try this.
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->get_where('tb_m_notaris', array('tb_m_notaris.id' => $id));
return $this->db->get()->row_array();
}
update this in your controller
$data['notaris'] = $this->m_notaris->tampil_edit($id);
you should pass like this in your controller
public function tampiledit($id) {
$id = ['tb_m_notaris.id' => $id];
$title['title'] = 'Notaris | Edit';
$data['notaris'] = $this->m_notaris->tampil_edit($id);
$this->load->view('template/headercss',$title);
$this->load->view('template/sidebar');
$this->load->view('template/navbar');
$this->load->view('master_data/notaris/edit', $data);
$this->load->view('template/footerjs');
}
public function tampil_edit($id) {
$this->db->select('tb_m_notaris.*,tb_m_user.email as email_notaris');
$this->db->from('tb_m_notaris');
$this->db->join('tb_m_user', 'tb_m_user.id=tb_m_notaris.id');
$this->db->where('tb_m_notaris.id', $id);
$query = $this->db->get();
return $query->result_array();
}
You need to update your query to this.
As id column exists in both the tables, you need to explicitly provide which table id you want to connect to by mentioning the table name.
I am trying to return customers from model Customer where id < 10. I do have some in the database.
$customers = Customer::where('id', '<', 10)->get();
return json_encode(['customers' => $customers]);
The above code will error out "Trailing data"
and when I try to dd($customers), I get a list of the collection Customer
I have no idea why I keep getting that and why the model is returning raw collection and not an object of the list of customers???
It seems like a null date "updated_at" field is causing the error. don't know why!
Solved By:
on the Customer model I had to do:
//ask Laravel to not manage default date columns
public $timestamps = false;
also I to mutate those columns:
public function setDateRemindedAttribute($value)
{
if (strlen($value)) {
$this->attributes['date_reminded'] = Carbon::createFromFormat('d/m/Y', $value);
} else {
$this->attributes['date_reminded'] = null;
}
}
public function setUpdatedAtAttribute($value)
{
if (strlen($value)) {
$this->attributes['updated_at'] = Carbon::createFromFormat('d/m/Y', $value);
} else {
$this->attributes['updated_at'] = $_SERVER['REQUEST_TIME'];
}
}
Use response()->json() like this
$customers = Customer::where('id', '<', 10)->get();
return response()->json(['customers' => $customers]);
First table (leads)
id, website, name, user_id
Second table (flags)
id, lead_id, user_id, info
What I am trying to do
Get all the user flags and each flag lead information.
what I have tried
Flag model
public function main()
{
return $this->belongsTo('App\Main', 'lead_id');
}
Flag Controller
public function getAgentFlags()
{
$agent_id = Auth::user()->id;
$flags = Flag::whereHas('main', function ($q) {
$q->where('user_id', '=', Auth::user()->id);
})->get();
dd($flags);
$totalleads = Flag::where('user_id', '=', $agent_id)->count();
return view('flags.my-flags')
->withLeads($leads)
->withTotalleads($totalleads);
}
What it returns
It returned wrong information as it return leads which is not equal to user ID.
I need to build a query with eloquent model including conditional where clause. I created something by searching google. But it doesn't seems to be working.
if ($status) {
$this->where('status', $status);
}
if ($assignedto) {
$this->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
$this->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $this->orderBy('date', 'desc')->paginate(40);
This one returns all results without the filtering of status, assigned to and dates.
I just updated it by assigning $this to a new variable because when I assigned the query to $this, it shown an error, $this cannot be over written.
$quoteModel = $this;
if ($status) {
$quoteModel = $quoteModel->where('status', $status);
}
if ($assignedto) {
$quoteModel = $quoteModel->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
$quoteModel = $quoteModel->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $quoteModel->orderBy('date', 'desc')->paginate(40);
which works perfectly now. But if somebody have some better option, please suggest. Thanks.
I added a scope to my model and call it from the controller. This way the actual filtering work is done in the model, the controller is just running the query through the filter scope.
Model:
I am getting URL parameters with Input::get, but you would also pass them as input parameters to the function.
public function scopeFilter($query)
{
$published = Input::get('published');
if (isset($published)) $query->where('published', '=', $published);
return $query;
}
Controller:
Here the query is run through the filter() before returning it to the view.
public function index()
{
return View::make('articles.index', [
'articles' => Article::with('writer')->filter()->get()
]);
}