shiro_

shiro_

Member Since 4 Months Ago

Experience Points
1,400
Total
Experience

3,600 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
1,400 XP
Nov
25
6 days ago
Activity icon

Started a new Conversation Eloquent Query Nested Relationships

I am writing a query to get the correct product_id where $stock->orderProduct->product->generic_name is equal to $item.

My relationships are:

class Stock extends Miioj
{
    public function orderProduct()
    {
        return $this->belongsTo(OrderProduct::class, 'order_product_id', 'id');
    }
class OrderProduct extends Miioj
{
    public function product()
    {
    return $this->belongsTo(Product::class, 'product_id', 'id');
    }
}

My code is as follows, but i keep getting an empty response. Any tips on what i am doing wrong will be highly appreciated.

$item = 'ABZ TAB ABZ TAB';

         $order_product = Stock::whereHas('orderProduct.product', function ($query) use ($item) {
            $query->where('generic_name', $item);
        })->with('orderProduct.product')->pluck('id')->first();

return $order_product;
Nov
19
1 week ago
Activity icon

Started a new Conversation Laravel Event Subscriber Error

I am trying to create a platform where a user can add a prescription. The prescriptions are loaded from a table called stocks. Stocks have oderProducts and orderProducts have products. When a user adds a prescription, the event prescription.added is called and the price of that specific item is updated in the invoiceItems table. When a user tries to add a prescription i get this error Trying to get property 'orderProduct' of non-object #0 C:\xampp\htdocs\medyq-web-core\modules\pharmacy\Listeners\PharmacySubscriber.php(72):. When i query the database to try and get stocks with OrderProducts, all the prescriptions appears. What is strange is that the code works on my localhost and another instance on my live server. Any assistance on what im doing wrong will be highly appreciated.

My code (PharmacySubscriber.ph) :

if ($paymentMode->is_scheme == config('constants.true')) {

            $invoiceItem->scheme_id = $paymentMode->scheme_id;
            $invoiceItem->payment_mode_id = null;

            $stock = Stock::where('id', $pharmacyEvent->prescription->product_id)
                ->whereHas('orderProduct.product.prices')
                ->with(['orderProduct.product.price' => function ($query) use ($paymentMode) {
                    $query->where('scheme_id', $paymentMode->scheme_id);
                }])->first();

            $price = $stock->orderProduct->product->price;

        } else {

            $invoiceItem->payment_mode_id = $paymentMode->payment_mode_id;
            $invoiceItem->scheme_id = null;


//this is the line with the error
            $stock = Stock::where('id', $pharmacyEvent->prescription->product_id)
                ->whereHas('orderProduct.product.prices')
                ->with(['orderProduct.product.price' => function ($query) {
                    $query->whereNull('scheme_id');
                }])->first();

            $price = $stock->orderProduct->product->price;

        }

My Stock model:

public function orderProduct()
    {
        return $this->belongsTo(OrderProduct::class, 'order_product_id', 'id');
    }

Nov
02
4 weeks ago
Activity icon

Replied to Php Artisan Migrate Command Generate Data In Multiple Schema's

For me, the schema name was saved in a table called $facility so i looped through all facilities and set the search path to be the schema name in my migration file. My code looks like this :

 public function up()
    {
        Schema::table('diseases', function (Blueprint $table) {

            $facilities = Facility::all();
        
            foreach($facilities as $facility) {

            $search_path = $facility['schema_name'];

            DB::statement("SET search_path = $search_path");

                Schema::table('diseases', function (Blueprint $table) {

                    $table->integer('disease_category_id')->nullable();

                });

            }
        });
    }
Oct
30
1 month ago
Activity icon

Started a new Conversation Laravel Seeder Running Out Of Memory

Hi, i have a seeder with about 33,000 records. I have been trying to seed data but all the methods i have tried keep resulting to memory running out. Any tips or advise on methods i can use to minimize the memory consumption will be highly appreciated. I am using laravel 5.8. The things i have commented out in my code below are methods i have tried out as well like setting the memory limit ini_set('memory_limit', '512M'); and //DB::setEventDispatcher(new Illuminate\Events\Dispatcher());.

Below is my seeder :

public function run()
    {
        //ini_set('memory_limit', '512M');
        
        DB::disableQueryLog();

        //DB::setEventDispatcher(new Illuminate\Events\Dispatcher());
        
        $tableName = env('DB_SCHEMA', 'public') . '.diseases';

        //DB::table($tableName)->truncate();

	$data = array( 
            
            array('uuid' => str::orderedUuid(), 'code'=> '1A00', 'name'=> 'Cholera', 'disease_category_id'=> '2', 			'description'=> 'Cholera', 'status'=> 1),
            array('uuid' => str::orderedUuid(),'code'=> '1A01', 'name'=> 'Intestinal infect', 'disease_category_id'=> '2','description'=> 'Typhoid fever','status'=> 1),
            array('uuid' => str::orderedUuid(),'code'=> '1A07.0','disease_category_id'=> '2','description'=> 'Typhoid peritonitis', 'status'=> 1 ),
);

$chunks = array_chunk($data, 5000);

        foreach ($chunks as $chunk) {
            DB::table($tableName)->insert($chunk);
        }

    }
Oct
27
1 month ago
Activity icon

Replied to 404 Error When Accessing Route

My view had a from with a missing post route.

Activity icon

Replied to 404 Error When Accessing Route

All of them are able to dd();

Activity icon

Replied to 404 Error When Accessing Route

Route::get('/{invoice}', function ($invoice) { dd("invoice"); }); output is "invoice" Route::get('/{invoice}/results', function ($invoice) { dd("invoice/results"); }); output is "invoice/results"

Activity icon

Replied to 404 Error When Accessing Route

It is a uuid, 91d18307-dc12-4752-81ad-52404d7f0ffa The route looks like this http://demo.medyq.localhost/laboratory/retail/91d18307-dc12-4752-81ad-52404d7f0ffa/results

Activity icon

Replied to 404 Error When Accessing Route

I still get a 404

Activity icon

Replied to 404 Error When Accessing Route

yes, it works when i remove Route::get('/{invoice}', '[email protected]_test_form')->name('laboratory.retail.show-tests-form');

Activity icon

Replied to 404 Error When Accessing Route

@bestmomo The route is listed there

Activity icon

Started a new Conversation 404 Error When Accessing Route

I have a list of items in an invoice which appear correctly in this route Route::get('/{invoice}', '[email protected]_test_form')->name('laboratory.retail.show-tests-form'); . I am trying to access individual items through this route Route::get('/{invoice}/results', '[email protected]')->name('laboratory.retail.results'); which brings a 404 error on the blade template despite the fact that everything is correct ie the correct item uuiid is passed on the route. My routes look like this :

Route::prefix('retail')->group(function () {
        Route::get('/{invoice}', '[email protected]_test_form')->name('laboratory.retail.show-tests-form');
        Route::get('/{invoice}/results', 'L[email protected]')->name('laboratory.retail.results');
        });   

I would really appreciate if anyone could help me understand why im getting a 404.

My controller looks like this

public function capture(Facility $facility, Invoice $invoice, LabTestItem $lab_test_item)
    {
        $invoice->load(['items']);

        $lab_test_item->responses;

        return view('laboratory::retail.lab-test-results')->with(['invoice' => $invoice, $lab_test_item ]);
   }
Oct
26
1 month ago
Activity icon

Awarded Best Reply on Laravel Postgres Select Schema In Loop

Instead of using set_schema to find a specific schema for a facility, i defined the search_path of the schema. My code now looks like this :

 $modules = Module::all();

            Facility::all()->each(function ($facility) use ($modules) {

		// i added these two lines

                $search_path = $facility['schema_name'];

		DB::statement("SET search_path = $search_path");

                foreach ($modules as $module) {

                    if ($module['in_built'] == false) {

                        Artisan::call('module:migrate', [
                            'module' => $module['name'],
                            '--subpath' => 'Updates',
                            '--force' => true,
                        ]);

                        /*Artisan::call('module:seed', [
                            'module' => $module['name'],
                            '--force' => true,
                        ]);
                        */

                        Artisan::call('module:publish', [
                            'module' => $module['name']
                        ]);

                    }

                }

            });

            Artisan::call('cache:clear');

            $this->info('Update Complete');

        }
Activity icon

Replied to Laravel Postgres Select Schema In Loop

Instead of using set_schema to find a specific schema for a facility, i defined the search_path of the schema. My code now looks like this :

 $modules = Module::all();

            Facility::all()->each(function ($facility) use ($modules) {

		// i added these two lines

                $search_path = $facility['schema_name'];

		DB::statement("SET search_path = $search_path");

                foreach ($modules as $module) {

                    if ($module['in_built'] == false) {

                        Artisan::call('module:migrate', [
                            'module' => $module['name'],
                            '--subpath' => 'Updates',
                            '--force' => true,
                        ]);

                        /*Artisan::call('module:seed', [
                            'module' => $module['name'],
                            '--force' => true,
                        ]);
                        */

                        Artisan::call('module:publish', [
                            'module' => $module['name']
                        ]);

                    }

                }

            });

            Artisan::call('cache:clear');

            $this->info('Update Complete');

        }
Oct
22
1 month ago
Activity icon

Started a new Conversation Laravel Postgres Select Schema In Loop

I am trying to write a laravel command that will enable me to update migrations in production. My database contains many schemas, one for each facility.

While trying to loop through each facility schema to update its schema, i keep getting an error Invalid schema name: 7 ERROR: no schema has been selected to create in at character 14") Is there a better way i can set a schema path in my loop? When i put an actual schema name in $facility['schema_name'] the migrations update successfully. Any recommendations will be appreciated, thanks.

My code :

 $modules = Module::all();

            Facility::all()->each(function ($facility) use ($modules) {

                set_schema($facility['schema_name']);

                foreach ($modules as $module) {

                    if ($module['in_built'] == false) {

                        Artisan::call('module:migrate', [
                            'module' => $module['name'],
                            '--subpath' => 'Updates',
                            '--force' => true,
                        ]);

                        /*Artisan::call('module:seed', [
                            'module' => $module['name'],
                            '--force' => true,
                        ]);
                        */

                        Artisan::call('module:publish', [
                            'module' => $module['name']
                        ]);

                    }

                }

            });

            Artisan::call('cache:clear');

            $this->info('Update Complete');

        }
Oct
17
1 month ago
Activity icon

Started a new Conversation Laravel NWidart Module Name With Spaces

Hi, I am trying to generate test data by creating seeders in my module called South Lake Analytics. When i run php artisan module:make-seed PermissionsSeeder South Lake Analytics i get this error. Too many arguments, expected arguments "command" "name" "module". Should i rename my module not to have spaces or how should o go about the name. Any tips or articles that can assist me will be appreciated. Thanks.

Oct
02
1 month ago
Activity icon

Started a new Conversation Laravel Project Not Reading Env File

I am setting up a laravel project, i have created a database and all the database details are correct in my env file. However, laravel seems not to be reading my .env file When i put the right or wrong credentials and run php artisan migrate or php artisan config:cache , i get this error

In Connection.php line 664:
                                                                                                                                           
  SQLSTATE[42601]: Syntax error: 7 ERROR:  zero-length delimited identifier at or near """"                                                
  LINE 1: select * from ""."facilities" where "subdomain" is null and ...                                                                  
                        ^ (SQL: select * from ""."facilities" where "subdomain" is null and ""."facilities"."deleted_at" is null limit 1)  
                                                                                                                                           

In Connection.php line 330:
                                                                                             
  SQLSTATE[42601]: Syntax error: 7 ERROR:  zero-length delimited identifier at or near """"  
  LINE 1: select * from ""."facilities" where "subdomain" is null and ...   

What could i be doing wrong? I have also enabled PDO in my php.ini file

My .env file looks like this :

APP_NAME="MedyQ"
APP_ENV=local
APP_KEY=*****
APP_DEBUG=true
APP_URL=http://medyq.localhost
APP_DOMAIN=medyq.localhost

LOG_CHANNEL=stack

DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=medyq
DB_SCHEMA=medyq
DB_USERNAME=medyq
DB_PASSWORD=*****
Sep
03
2 months ago
Activity icon

Awarded Best Reply on Two Dimensional Array - How To Sum Array Elements With Duplicate Element Value

This worked for me

$num = $requests->map(function ($row) {

            $result = array();

            $ttl = $row->sum('amount_paid');

            $row = $row->toArray();

            $final_array = [];

            foreach($row as $arr){
            $final_array[$arr['payment_name']]['payment_name'] = $arr['payment_name'];
            $final_array[$arr['payment_name']]['amount_paid'] = (isset($final_array[$arr['payment_name']]['amount_paid']))? $final_array[$arr['payment_name']]['amount_paid']+$arr['amount_paid'] : $arr['amount_paid'];    
            }
            $final_array = array_values($final_array);

            return $final_array;
        });
Activity icon

Replied to Two Dimensional Array - How To Sum Array Elements With Duplicate Element Value

This worked for me

$num = $requests->map(function ($row) {

            $result = array();

            $ttl = $row->sum('amount_paid');

            $row = $row->toArray();

            $final_array = [];

            foreach($row as $arr){
            $final_array[$arr['payment_name']]['payment_name'] = $arr['payment_name'];
            $final_array[$arr['payment_name']]['amount_paid'] = (isset($final_array[$arr['payment_name']]['amount_paid']))? $final_array[$arr['payment_name']]['amount_paid']+$arr['amount_paid'] : $arr['amount_paid'];    
            }
            $final_array = array_values($final_array);

            return $final_array;
        });
Sep
02
2 months ago
Activity icon

Started a new Conversation Two Dimensional Array - How To Sum Array Elements With Duplicate Element Value

I have a multi array that has some duplicated values that are same by payment_name ( payment_name is an element ) I want to sum quantity of each array that has same payment_name.

My variable $num looks like this :

array( 
    'items' => array ( 
        '2020-08-04' => array ( 
            0 => array ( 
                0 => array ( 
                    'payment_name' =>'Cash',
                    'amount_paid' => array (
                        0 => '0', 
                    ),
                ), 
            ), 
            1 => 0, 
        ),
        '2020-08-05' => array ( 
            0 => array( 
                0 => array ( 
                    'payment_name' => 'Cash', 
                    'amount_paid' => array ( 
                            0 => '0', 
                            1 => '0', 
                            2 => '165', 
                    ), 
                ),
                1 => array ( 
                    'payment_name' => 'Mpesa', 
                    'amount_paid' => array ( 
                            0 => '0', 
                            1 => '0',
                            2 => '165', 
                    ), 
                ), 
            ), 
            1 => 165, 
        ), 

My expected array should be like this, the amount paid should be the total, not an array of all amounts:

array( 
    'items' => array ( 
        '2020-08-04' => array ( 
            0 => array ( 
                0 => array ( 
                    'payment_name' =>'Cash',
                    'amount_paid' => "0"
                ), 
            ), 
            1 => 0, 
        ),
        '2020-08-05' => array ( 
            0 => array( 
                0 => array ( 
                    'payment_name' => 'Cash', 
                    'amount_paid' => "0"
                ),
                1 => array ( 
                    'payment_name' => 'Mpesa', 
                    'amount_paid' => "165" 
                ), 
            ), 
            1 => 165, 
        ), 

My code is as below

$requests = $builder->get()->groupBy('date');

        $num = $requests->map(function ($row) {

            $result = array();

            $ttl = $row->sum('amount_paid');

            $row = $row->toArray();

            $names = array_column($row, 'payment_name');
            $amount = array_column($row, 'amount_paid');

            $unique_modes = array_unique($names);

            foreach ($unique_modes as $name) {
                $this_keys = array_keys($names, $name);
                $qty = array_sum((array_intersect_key($amount, array_combine($this_keys, $this_keys))));
                $result[] = array("payment_name"=>$name, "amount_paid"=>$amount);
            }
            
            return [$result, $ttl ];
        });

        return $num;
Aug
31
3 months ago
Activity icon

Started a new Conversation Imploding Collections After Grouping Them

My collection looks like this

array:2 [
  2020-08-01 [
    0: [
      "date" => 2020-08-01
      "payment_name" => "Cash"
      "sales_count" => "200"		
      ]
    ]
    1 => array:1 [
      "date" => 2020-08-01
      "payment_name" => "Scheme"
      "sales_count" => "100"		
      ]
    ]		
    2 => array:2 [
      "date" => 2020-08-01
      "payment_name" => "Scheme"
      "sales_count" => "0"		
      ]
    ]
  ]
  2020-05-02 [
    0: [
      "date" => 2020-05-02
      "payment_name" => "Cash"
      "sales_count" => "200"		
      ]
    ]
  ]
]

I would like my data to appear in a way that the date, sum and all payment names appear like this:

2020-050-01 : "payment_modes" => Cash and Scheme, "total " =>100

My code is as below

return $requests = $builder->get();

        $num = $requests->groupBy('date')->map(function ($row) {
            $row->sum('amount_paid');
            $row->pluck('payment_name')->implode(' & ');
        })->implode(' and. ');

return $num;
Aug
28
3 months ago
Activity icon

Replied to Calculate The Sum Of Elements And List Elements If Have The Same Date

Let me try this, my array is multidimensional

Aug
27
3 months ago
Activity icon

Started a new Conversation Calculate The Sum Of Elements And List Elements If Have The Same Date

I have an array that looks like this:

Array
(
[0] => Array
    (
        [date] => 2015-07-07
        [payment_name] => Cash
    )

[1] => Array
    (
        [date] => 2015-07-10
        [payment_name] => Card
    )

[2] => Array
    (
        [date] => 2015-07-07
        [payment_name] => Mobile Money
    )

I am trying to calculate the sum of elements if they have the same date,as well as show all payment names that have the same date. For now, i have managed to display the calculated sum but i am having a hard time displaying the payment names as well. Only the first payment name comes with an undefined index. Any tips on how i can do this?

$requests = $builder->get(); 

        $aggregateArray = array();

        foreach($requests as $row) {
                if(!array_key_exists($row['date'], $aggregateArray)) {
                    $aggregateArray[$row['date']] = 0;
                }
                $aggregateArray[$row['date']] += $row['sales_count'];
                $aggregateArray[$row['payment_name']]; 
            } 

        return $aggregateArray;
Aug
26
3 months ago
Activity icon

Started a new Conversation Posting Checkbox Filter Values For Charts In Tabs

I have a checkbox filter for my charts(chartjs) which works on single charts perfectly but does not seem to work with the charts in tabs. The same filter should be applied to all charts. The value from the filter is sent to my server but the response returns all the data instead of filtered data. Should i use a different approach with checkboxes and tabs? I will appreciate links to useful articles too. My checkbox looks like this:

                          <div class="col-md-2">
                                <label class="control-label">&nbsp;</label>
                                <div class="checkbox">
                                    <label style="padding-left: 0;">
                                        <input type="checkbox" id="emergency"
                                            value="{{config('constants.true')}}">
                                        <span class="cr"><i class="cr-icon fa fa-check"></i></span>
                                        Emergency
                                    </label>
                                </div>
                            </div>

This is where i send the value of the checkbox

request({
                url: '{{route('my_route')}}',
                data: {
                    is_emergency: isEmergency.is(':checked') ? 1 :0,
                },

This is how i send my request in laravel

$is_emergency = (int)request('is_emergency', 0);

if ($is_emergency === 1) {

            $builder->whereHas('visit', function ($query) use ($is_emergency) {
                $query->where('is_emergency', $is_emergency);
            });

}
Aug
20
3 months ago
Activity icon

Replied to Laravel Eloquent WhereHas After Union

I have two queries because my table has two foreign keys. I will read this article, thanks

Activity icon

Replied to Laravel Eloquent WhereHas After Union

Yes, i get the correct results if i run the queries independently

Aug
19
3 months ago
Activity icon

Started a new Conversation Laravel Eloquent WhereHas After Union

I have two queries, i am combining them using a union. The result of this query is then filtered using a whereHas . Problem is , the filtered results are inaccurate, only one of the filtered results is correct . Any ideas on how i can get more accurate results after doing the union?

$builder1 = LabTestVisit::select(
            DB::raw("count(*) as payment_count"),
            DB::raw("schemes.name as payment_name")
        )
        ->join('payment_mode_visits', 'payment_mode_visits.visit_id', 'lab_test_visits.visit_id')
        ->leftJoin('schemes', 'schemes.id', 'payment_mode_visits.scheme_id')
        ->whereNotNull('schemes.name')
        ->groupBy('schemes.name');

 $builder = LabTestVisit::select(
            DB::raw("count(*) as payment_count"),
            DB::raw("payment_modes.name as payment_name")
        )
            ->join('payment_mode_visits', 'payment_mode_visits.visit_id', 'lab_test_visits.visit_id')
            ->join('payment_modes', 'payment_modes.id', 'payment_mode_visits.payment_mode_id')
            ->groupBy('payment_modes.name')
            ->whereNotNull('payment_modes.name')
            ->union($builder1);

$clinics = request('clinics', []);

        if (!empty($clinics) && is_array($clinics)) {
            $builder->whereHas('visit.clinic', function ($query) use ($clinics) {
                $query->select([
                    DB::raw("DISTINCT *"),
                    DB::raw("count(*) OVER() AS filtered")
                ]);
                $query->whereIn('uuid', $clinics);
            });
        }
Aug
18
3 months ago
Activity icon

Started a new Conversation Laravel Eloquent Query Passing Variables

I have a query that gives me a very large dataset of invoices. I am trying to get invoices only in a particular category using the where clause by passing a variable called lab_tests that contains all the category items . I keep getting this error SQLSTATE[HY093]: Invalid parameter number: parameter was not defined Is there a better way to pass the variable or filter out the categories?

My code

$lab_tests = LabTest::active()->orderBy('name', 'DESC')->get();

        $builder = InvoiceItem::select(
            DB::raw("date_closed"),
            DB::raw("invoices.number as invoice_number"),
            DB::raw("patients.first_name"),
            DB::raw("patients.last_name"),
            DB::raw("clinics.name"),
            DB::raw("invoice_items.name AS service_name"),
            DB::raw("invoice_items.total_amount"),
            DB::raw("invoice_items.amount_paid"),
            DB::raw("invoice_items.balance"),
            DB::raw("schemes.name as payment_mode")
            )
            ->join('invoices', 'invoices.id', 'invoice_items.invoice_id')
            ->join('payment_mode_visits', 'payment_mode_visits.visit_id', 'invoices.visit_id')
            ->join('schemes', 'schemes.id', 'payment_mode_visits.scheme_id')
            ->join('visits', 'visits.id', 'invoices.visit_id')
            ->join('patients', 'patients.id', 'visits.patient_id')
            ->join('clinics', 'clinics.id', 'visits.clinic_id')
            ->whereNotNull('date_closed')
            ->where('invoice_items.name', '=', $lab_tests);
            
        $invoices = $builder->get();

        return $invoices;
Aug
14
3 months ago
Activity icon

Started a new Conversation Show/Hide Data From Barchart With Chart.js/Laravel

I am creating a chart using chartjs and laravel. I am trying to create filters for data using the label in the dataset.

For now my label displays as an array of all the labels that exsist in the chat. Any ideas how i can display the labels seperately?

My code:

$data = [
            "labels" => [],
            "datasets" => [
                [
                    'label' => [],
                    'data' => [

                    ]
                ]
            ]
        ];

$lobs = $builder->get()->map(function ($lob) {
            $lob->payment_mode;
            return $lob;
        })->sortBy(function ($obj, $key) {
            return $obj->payment_mode;
        });

        foreach ($lobs as $lob) {

            $data['labels'][] = $lob->payment;
            $data['datasets'][0]["data"][] = $lob->lab_payment_count;
            $data['datasets'][0]["label"][] = $lob->payment;

        }

        return $data;
Aug
13
3 months ago
Activity icon

Replied to Laravel Accessing A Relationship Table

i get this error SQLSTATE[42803]: Grouping error: 7 ERROR: column "invoice_items.id" must appear in the GROUP BY clause or be used in an aggregate function LINE

And when i add the id i get a response where everything is null

Activity icon

Started a new Conversation Laravel Accessing A Relationship Table

I have a table called invoices. An invoice has many items.

    {
        return $this->hasMany(InvoiceItem::class);
    }

I am trying to get the sum of items that have been paid from a column called total_amount in the items table. My query is returning null . Is there another method i can use to access the items?

My code

$builder = Invoice::with(['items' => function ($query) {
            $query->select(
                DB::raw("SUM(total_amount) as lab_count"),
                DB::raw('name')
            )
            ->whereNotIn('name', ['Consultation','Appointment', 'Laboratory', 'HIV Counselling'])
            // ->whereBetween('created_at', [$start_date, $end_date])
            ->groupBy(DB::raw('name'));
        } ]);
Aug
12
3 months ago
Activity icon

Started a new Conversation Laravel Add Relationship Constraints And Get Count

I am trying to get the count of lab results that a visit has so that filtering records can be easy. A visit can have many lab results. The lab_test_results contains a visit_id. I tried running a query after joining the two table but the filter still failed. So i tried this method. Any suggestions on another method i can use?

I am getting this error

SQLSTATE[42P01]: Undefined table: 7 ERROR: missing FROM-clause entry for table "visits" LINE 1: ... OVER() AS filtered from "lab_test_results" where "visits"."... ^ (SQL: select DISTINCT *, count(*) OVER() AS filtered from "lab_test_results" where "visits"."id" = "lab_test_results"."visit_id" and "lab_test_results"."deleted_at" is null)

My code

$builder->whereHas('visit.labTestsResults', function ($query) use ($lab_tests) {
            $query->select([
                DB::raw("DISTINCT *"),
                DB::raw("count(*) OVER() AS filtered")
            ])->get();
            $query->whereIn('uuid', $lab_tests);
        });  
 return $builder;
Aug
11
3 months ago
Activity icon

Awarded Best Reply on Chartjs Passing Array Group Counts In Y-axis

Yes, i converted the response to an array of numbers

Activity icon

Replied to Chartjs Passing Array Group Counts In Y-axis

Yes, i converted the response to an array of numbers

Activity icon

Replied to Laravel Cannot Accessing Data In Provider In All My Views

@sinnbeck $invoices returns this

Closure() {#1016 ▼
  class: "Modules\SouthLakeAnalytics\Providers\ReportsServiceProvider"
  this: Modules\SouthLakeAnalytics\Providers\ReportsServiceProvider {#193 …}
  file: "/var/www/html/medyq-web-core/modules/SouthLakeAnalytics/Providers/ReportsServiceProvider.php"
  line: "42 to 72"
}
Activity icon

Replied to Laravel Cannot Accessing Data In Provider In All My Views

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "invoice_items" does not exist LINE 1: ...tients"."first_name", "patients"."last_name" from "invoice_i... ^...

But the exact code works in a controller

Activity icon

Started a new Conversation Laravel Cannot Accessing Data In Provider In All My Views

I have a provider called ReportsServiceProvider which looks like this:

public function boot()
     {
        {
            $builder = DB::table('invoice_items')
            ->select(
                [
                    DB::raw("DISTINCT invoice_items.uuid"),
                    'invoices.number AS invoice_number',
                    'invoices.date_closed',
                    'invoice_items.name AS service_name',
                    'invoice_items.total_amount',
                    'invoice_items.amount_paid',
                    'invoice_items.balance',
                    'visits.created_at',
                    'payment_mode_visits.payment_mode',
                    'visits.id AS visit_id',
                    'visits.ended_at',
                    'clinics.name',
                    'patients.first_name',
                    'patients.last_name',
                    
                ]
            )
            ->join('invoices', 'invoices.id', 'invoice_items.invoice_id' )
            ->join('visits', 'visits.id', 'invoices.visit_id')
            ->join('patients', 'patients.id', 'visits.patient_id')
            ->join('clinics', 'clinics.id', 'visits.clinic_id' ) 
            ->leftJoin('payment_mode_visits', 'payment_mode_visits.visit_id', 'invoices.visit_id')
            ->where('invoice_items.amount_paid', '>', 0);

            $invoices = $builder->get();

            View::share('invoices', $invoices);
        }

    }

I am trying to access $invoices in a blade template but its an undefined variable. Have i missed anything or should i import anything in my view so that i can access the invoices variable in all views

Aug
10
3 months ago
Activity icon

Started a new Conversation Chartjs Passing Array Group Counts In Y-axis

I am creating a chart using chartjs. Its has clinics on the x axis and the counts on the y axis. I have managed to to the x axis but im having a hard time passing the counts on the y axis. My object looks like this

"Comprehensive Care Clinics": 9
​
"Dental Clinic": 5
​
"Dermatology Clinic": 4
​
"Gastroenterology Clinic": 3
​
"Gynaecology Outpatient Clinic": 9
​
"Medical Outpatient Physician": 4
​
"Nutrition Clinic": 2
​
Oncology: 4
​

My chart looks like this:

<script>

	var url = "{{url('myurl') }}";
    var Clinics = new Array();

    $(document).ready(function() {
        $.get(url, function(response) {
			console.log(response)

            const xlabels = Object.keys(response)
			
            const ctx = document.getElementById("clinicChart").getContext('2d');
            const myChart = new Chart(ctx, {
                type: 'bar',
                data: {
					labels: xlabels,    
					    datasets: [{
							fillColor: "#79D1CF",
							strokeColor: "#79D1CF",
							label: 'Patient Visits',
							data: response,
							borderWidth: 1
						}]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero:true
                            }
                        }],
					
                    }
                }
            })
        })
    })
</script>
Aug
04
3 months ago
Activity icon

Started a new Conversation Add Other Values Of Object To Array Based On Foreign Key

I am trying to return the occurence of diseases in an array based on the occurrence of the disease_id in the table. For now my response shows the foreign key and its count.

data :{
2016	1
2017	1
2018	1
2019	1
2020	1
}

I would want to show the disease name and occurence so that my array can be:

data :{
disease_name	 1
disease_name	1
disease_name	1
disease_name		1
disease_name		1
}

I have tried pushing the disease name to the diagnosis collection but i get the error Property [disease] does not exist on this collection instance.

My code

public function diagnosis_diseases(Disease $disease) {

        $diagnosis = DB::table('diagnoses')->get();

        $collection = collect($diagnosis);

        $disease_name = $diagnosis->disease;

        $collection->push($disease_name);

        dd($collection);

        $counts = $diagnosis->groupBy('disease_id')->map->count();

        return ['data' => $counts];

    }
Aug
03
3 months ago
Activity icon

Replied to Laravel Get All Tables With A Foreign Key Visit_id

The diagnoses migration is in a module The visits migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateVisitsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('visits')) {
            Schema::create('visits', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->uuid('uuid')->unique();
                $table->unsignedInteger('patient_id');
                $table->unsignedInteger('clinic_id');
                $table->enum('is_emergency', [config('constants.yes'), config('constants.no')]);
                $table->string('number')->nullable();
                $table->timestamp('ended_at')->nullable();
                $table->unsignedInteger('created_by')->nullable();
                $table->unsignedInteger('updated_by')->nullable();
                $table->unsignedInteger('deleted_by')->nullable();
                $table->unsignedInteger('restored_by')->nullable();
                $table->timestamp('restored_at')->nullable();
                $table->timestamps();
                $table->softDeletes();

                $table->foreign('patient_id')->references('id')->on('patients')->onDelete('cascade');

                $parentSchema = env('DB_SCHEMA', 'public');

                $table->foreign('created_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');
                $table->foreign('updated_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');
                $table->foreign('deleted_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');
                $table->foreign('restored_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');

                $table->index(['uuid']);
            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('visits');
    }
}

The diagnosis migration

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateDiagnosesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        if (!Schema::hasTable('diagnoses')) {

            Schema::create('diagnoses', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->uuid('uuid')->unique();
                $table->unsignedBigInteger('visit_id');
                $table->unsignedBigInteger('disease_id')->nullable();
                $table->text('description');
                $table->boolean('primary')->default(false);
                $table->boolean('confirmed')->default(false);
                $table->unsignedInteger('created_by')->nullable();
                $table->unsignedInteger('updated_by')->nullable();
                $table->unsignedInteger('deleted_by')->nullable();
                $table->unsignedInteger('restored_by')->nullable();
                $table->timestamp('restored_at')->nullable();
                $table->timestamps();
                $table->softDeletes();

                $table->index(['uuid']);

                $parentSchema = env('DB_SCHEMA', 'public');

                $table->foreign('visit_id')->references('id')->on('visits')->onDelete('cascade');
                $table->foreign('disease_id')->references('id')->on('diseases')->onDelete('set null');
                $table->foreign('created_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');
                $table->foreign('updated_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');
                $table->foreign('deleted_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');
                $table->foreign('restored_by')->references('id')->on($parentSchema . '.users')->onDelete('set null');


            });
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public
    function down()
    {
        Schema::dropIfExists('diagnoses');
    }
}
Activity icon

Started a new Conversation Laravel Get All Tables With A Foreign Key Visit_id

I have a table visits which has name, patient_id, gender . I would like to add more details to the visit object by accesing tables with the visit_id. For now I have tried to get some data from the diagnoses table and defined the relationships but my data is empty.

My code looks like this:

Entities/Visit.php

public function diagnoses()
    {
        return $this->hasMany(Diagnosis::class);
    }

    public function primaryDiagnoses()
    {
        return $this->hasMany(Diagnosis::class)->where('primary', true);
    }

My controller

$builder = Visit::select(
            DB::raw("DISTINCT *"),
            DB::raw("count(*) OVER() AS filtered")
        )->whereBetween('created_at', [$start_date, $end_date]);

        $insurance = request('insurance', []);
        $payment_mode = request('payment_mode_visits', []);
        $pament_mode_scheme = request('payment_mode_visits_schemes', []);
	$diagnoses = request('diagnoses', []);

} 

if(!empty($diagnoses) && is_array($diagnoses)) {

            $diagnoses = Visit::with('diagnoses')->get();

            var_dump($diagnoses);
}
Aug
01
4 months ago
Activity icon

Awarded Best Reply on Laravel Postgres Sql State Error Zero Length Delimited

Seems like i had not specified my DB_SCHEMA on my .env file

Activity icon

Replied to Laravel Postgres Sql State Error Zero Length Delimited

Seems like i had not specified my DB_SCHEMA on my .env file

Jul
31
4 months ago
Activity icon

Started a new Conversation Laravel Postgres Sql State Error Zero Length Delimited

I am getting this error SQLSTATE[42601]: Syntax error: 7 ERROR: zero-length delimited identifier at or near """" LINE 1: select * from ""."facilities" where "subdomain" = $1 and "st... ^ (SQL: select * from ""."facilities" where "subdomain" = southlake and "status" = 1 and exists (select * from ""."organizations" where ""."facilities"."organization_id" = ""."organizations"."id" and "status" = 1 and ""."organizations"."deleted_at" is null) and ""."facilities"."deleted_at" is null limit 1) before and after i seed data to postgres.

Is there a package i have not installed?

my code in the service provider

Route::bind('subdomain', function ($subdomain) {
				
				$facility = Facility::where('subdomain', $subdomain)
						->active()
						->whereHas('organization', function ($query) {
							$query->active();
						})
						->with('modules')->firstOrFail();
				
				$alias = get_path_alias();
				
				$allowedPaths = array_merge(get_facility_non_module_paths(), get_auth_paths());
Jul
30
4 months ago
Activity icon

Awarded Best Reply on Laravel Mysql Schema Migration

I just figured out why, im using mysql instead of postgres

Activity icon

Replied to Laravel Mysql Schema Migration

I just figured out why, im using mysql instead of postgres

Activity icon

Replied to Laravel Mysql Schema Migration

I want to add the SCHEMA_OWNER in information_schema.schemata,