whereJsonContains not returning anyting - php

I have the following blocks of code
try {
$data = Checklist::where('setupStatus', true)->whereJsonContains('workspaceRegions', $regionID)->orderBy('id', 'desc')->paginate(5);
return response()->json([
'data' => $data
], 200);
} catch (\Throwable $th) {
return $th;
}
This works as expected and returns the correct checklists.
So then I did the same in the next block, but this time I have to iterate through and array to get the id values to search for. This always return an empty array though
$company = Auth::user()->company;
try {
$hodIDs = CompanyRoles::where('hod', true)->get();
$hods = [];
foreach ($hodIDs as $option) {
$id = strval($option->id);
$hods = User::where('companyID', $company->id)->whereJsonContains('companyRoles', $id)->with('employee')->get();
}
return response()->json([
'message' => 'success',
'hods' => $hods
], 200);
} catch (\Throwable $th) {
return $th;
}
The 'companyRoles' column is an array that contains something like ["1","2"]
How can I return each user with and hodID within the companyRoles column array?
The following gives me what I want, but this feels a bit like a hack.
$hods = [];
foreach ($hodIDs as $option) {
$id = strval($option->id);
$user = User::where('companyID', $company->id)->whereJsonContains('companyRoles', $id)->with('employee')->first();
if ($user) {
array_push($hods, $user);
}
}
Thanking you in advance

Related

How to show json encoded array in Sweet alert message

I'm using Laravel 8 and Sweet Alert and I wanted to show the error messages that were caught by error Exception as Sweet Alert error popup message.
Basically here is my Controller method:
try{
...
}catch(\Exception $e){
// Alert::error('Error Title', 'Error Message');
return json_encode(['status' => '500', 'msg' => __('message.error-server')]);
}
So as you can see I have json encoded an associative array that holds the information of the error message but I don't want to return it. In fact I have to show it as Alert::error(...).
So how can I do that?
UPDATE 1:
I just tested this but not showing me the error as Alert:
public function destroy(User $user)
{
try{
$useradasd->is_active = 0;
$useradasd->is_deleted = 1;
$useradasd->remover_id = Auth::id();
$useradasd->save();
}catch(\Exception $e){
$attributes = ['status' => '500', 'msg' => __('message.error-server')];
$dataAttributes = array_map(function($value, $key) {
return $key.'=>'.$value;
}, array_values($attributes), array_keys($attributes));
$associativeString = implode(', ', $dataAttributes);
Alert::error($associativeString);
}
Alert::success('Removed', 'That user is deleted');
return back();
}
UPDATE 2:
I just tried this, but does not catch the error exception and show me the Alert::success(...) instead.
public function destroy(User $user)
{
try{
$useradasd->is_active = 0;
$useradasd->is_deleted = 1;
$useradasd->remover_id = Auth::id();
$useradasd->save();
}catch(\Exception $e){
$attributes = ['status' => '500', 'msg' => __('message.error-server')];
$dataAttributes = array_map(function($value, $key) {
return $key.'=>'.$value;
}, array_values($attributes), array_keys($attributes));
$associativeString = implode(', ', $dataAttributes);
Alert::error('Error',$associativeString);
}
Alert::success('Removed', 'That user is deleted');
return back();
}
UPDATE #3:
I can finally get the error:
But I wanted to show $attributes['status'] which is 500 as Error Title and the body of that error contains $attributes['msg']. How can I do that?
You can do this:
$attributes = ['status' => '500', 'msg' => __('message.error-server')
$dataAttributes = array_map(function($value, $key) {
return $key.'=>'.$value;
}, array_values($attributes), array_keys($attributes));
$associativeString = implode(', ', $dataAttributes);
What this does basically is, it will convert the associative array to string first and then you can use the final string i.e.$associativeString in your alert as:
Alert::error($associativeString);
this will output like:
status => 500, msg => Internal Server Error
you can modify return $key.'=>'.$value; inside map to shape the final output the way you want.
UPDATE #1
Looking at the SweetAlert docs you used, I believe it follows the syntax of Alert::[type]([Title],[message]), You can update the alert from this:
Alert::error($associativeString);
to this:
Alert::error('Error',$associativeString);
UPDATE #2
public function destroy(User $user)
{
try{
$useradasd->is_active = 0;
$useradasd->is_deleted = 1;
$useradasd->remover_id = Auth::id();
$useradasd->save();
throw new Exception("Custom Exception from try block");
}catch(\Exception $e){
$attributes = ['status' => '500', 'msg' => $e->getMessage()];
$dataAttributes = array_map(function($value, $key) {
return $key.'=>'.$value;
}, array_values($attributes), array_keys($attributes));
$associativeString = implode(', ', $dataAttributes);
Alert::error('Error',$associativeString);
}
return back();
}
UPDATE #3
You should work on improving your concepts of arrays in php and how they work learn How PHP associative arrays work, now according to your requirement you should not convert the associative array to string as I suggested in my original answer. try this instead:
public function destroy(User $user)
{
try{
$useradasd->is_active = 0;
$useradasd->is_deleted = 1;
$useradasd->remover_id = Auth::id();
$useradasd->save();
throw new Exception("Custom Exception from try block");
}catch(\Exception $e){
$attributes = ['status' => '500', 'msg' => $e->getMessage()];
Alert::error($attributes['status'],$attributes['msg']);
}
return back();
}
the Alert::error() takes two parameters the first one is Title and the second is the message, you just have to fetch the value from related keys of associative array i.e. status and msg in our case.
This Should Work
Alert::error(json_encode(['status' => '500', 'msg' => __('message.error-server')],JSON_PRETTY_PRINT));

Where like not working inside foreach loop in laravel

Where like not working inside foreach loop in Laravel. The following always return null. Here i want to use multi sorting, but the response in always blank.
public function searchBy(Request $request)
{
if($request->name!=''){
$data['name']=$request->name;
}
if($request->s_name!=''){
$data['short_name']=$request->s_name;
}
if($request->pin!=''){
$data['pin_code']=$request->pin;
}
if($request->city!=''){
$data['city']=$request->city;
}
$customers = Customer::get();
foreach ($data as $key => $value) {
// return $key;
$customers = $customers->where($key,'LIKE','%'.$value.'%');
}
return response()->json([
'data' =>$customers,
]);
}
The variable $customers should be a QueryBuilder and you should call get() on it in the end to retrieve your items.
$customers = Customer::query();
foreach ($data as $key => $value) {
$customers->where($key,'LIKE','%'.$value.'%');
}
return response()->json([
'data' => $customers->get(),
]);
The QueryBuilder is an object, which is by design pass by reference, therefor you do not need to reassign it.

how to check if data already exist when insert data

I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.
My code:
$obj = new Pengajuan();
// $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));
Above of the code add a validation like below:
$this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;
And then rest of your controller code.
try this:
public function store(Request $request)
{
$this->validate($request,[
'id_nasabah'=>'required|exists:your_table_name,id',
'tgl_pengajuan'=>'more_validations',
'besar_pinjaman'=>'more_validations',
]);
//if $this->validate() fails, it will return a response 422 code error
//else it will continue with the creation of your object
//is a good idea to use a try-catch in case of something goes wrong
try
{
$pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));
return response->json([
'pengajuan'=>$pengajuan,
'status'=>'Tersmpan',
],200);//return a http code 200 ok
}
catch(Exception $e)
{
//'message'=>'this will return what is the error and line'
return response()->json([
'message'=>$e->getMessage().'/'.$e->getLine(),
'status'=>'Gagal',
],422);
}
}

creating multiple rows based on record in an array - laravel

I have the following query that brings back an array of user_ids, where each user will get notified.
$pstusrmembs = DB::table('postusrs')
->where('post_id', $post_id)
->where('accepted', 1)
->pluck('user_id');
I need to put each user_id in a different row in the below "insert" code :
$notifs = new Notif();
$notifs->rec_uid = $pstusrmembs;
$notifs->title = $post_title;
$notifs->save();
How can I change $notifs->rec_uid = $pstusrmembs; to do this ?
Use for loop for this:
foreach($pstusrmembs as $userID){
$notifs = new Notif();
$notifs->rec_uid = $userID;
$notifs->title = $post_title;
$notifs->save();
}
And If You are using the Mass Assignment concept
foreach ($pstusrmembs as $userID) {
Notif::create(['rec_uid' => $userID, 'title' => $post_title]);
}
And If You are using the Mass Assignment concept Without Any Model
Events or Listeners
foreach ($pstusrmembs as $userID) {
$arrayOfNotif[] = ['rec_uid' => $userID, 'title' => $post_title];
}
Notif::insert($arrayOfNotif);
I will recommend to use DB transaction to keep a database consistent even in cases of system failure and prepare that list as array and insert in one line ....
$prepare = [];
foreach($pstusrmembs as $p) {
$prepare[] = [
'rec_id' => $p,
'title' => $post_title
];
}
DB::beginTransaction();
try {
Notif::insert($prepare);
DB::commit();
} catch (Exception $e) {
DB::rollback();
}

Laravel Property does not exist on this collection instance

I need to transfer data from Mysq table (Paniers) to another Mysql table (Commandes) and delete the data from first table after transfer.
Here is my code:
function Commande(Request $request) {
$pn = $request->input('id');
$pdr = Panier::find($pn);
$user = Commande::create([
'ID_User' => $pdr->ID_User,
'ID_Piece' => $pdr->ID_Piece,
'QTE' => $pdr->QTE,
]);
if($user){
if($pdr->delete())
{
echo 'Commande Confirmée';
}
}
}
I get this error:
"Property [ID_User] does not exist on this collection instance."
If i do this it works but instead of getting all data i only get the first line. I need to get all lines of data!
$pdr = Panier::find($pn)->first();
If $pn is array Panier::find($pn) returns collection not entity so you should iterate it
Panier::find($pn)->each(function($pdr){
$user = Commande::create([
'ID_User' => $pdr->ID_User,
'ID_Piece' => $pdr->ID_Piece,
'QTE' => $pdr->QTE,
]);
if($user){
if($pdr->delete())
{
echo 'Commande Confirmée';
}
}
});
When you are doing :
$pdr = Panier::find($pn);
If the record does not exist, it will return null. Then if you do $pdr->ID_User it is going to throw an error. Please check beloew updates :
<?php
function Commande(Request $request) {
$pn = $request->input('id');
$pdr = Panier::find($pn);
// Model not found
if(!$pdr){
return response()->json(['msg' => 'No records found']);
}
// Create new Commande
$user = Commande::create([
'ID_User' => $pdr->ID_User ?? 'default_value_for_ID_User',
'ID_Piece' => $pdr->ID_Piece ?? 'default_value_for_ID_Piece',
'QTE' => $pdr->QTE ?? 'default_value_for_QTE'
]);
// If user is created
if($user){
// Delete Panier
$pdr->delete();
return response()->json(['msg' => 'Success']);
}
return response()->json(['msg' => 'Could not create new Commande']);
}
For above to work you need to have :
Columns ID_User, ID_Piece and QTE marked as $fillable = [] in Commande Model.
You need to have a basic primary key for Panier Model, otherwise delete() will not work.
You can do it by findOrFail and handling Exception:
function Commande(Request $request) {
$pn = (int) $request->input('id');
try {
$pdr = Panier::findOrFail($pn);
$pdr->each(function ($item, $key) {
$user = Commande::create([
'ID_User' => $item->ID_User,
'ID_Piece' => $item->ID_Piece,
'QTE' => $item->QTE,
]);
if ($user && $item->delete()) {
echo 'Commande Confirmée';
}
});
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
//#Todo handle error
}
}
According to laravel 5.0 documents:
Retrieving A Model By Primary Key Or Throw An Exception
Sometimes you may wish to throw an exception if a model is not found. To do this, you may use the firstOrFail method:
Collection

Categories