mprythero

mprythero

Member Since 1 Year Ago

Experience Points 5,610
Experience Level 2

4,390 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 29
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

30 Mar
1 month ago

mprythero left a reply on Adding A Relationship To A Pivot Table Of A Polymorphic Relationship

@STAUDENMEIR - It seems close to what I want to do but I'm not quite sure how I would go about implementing this and the morph, I'm not seeing any examples of both used together...

mprythero started a new conversation Adding A Relationship To A Pivot Table Of A Polymorphic Relationship

I have a model called Invoice and it has the following relationships:

public function manifests(){
    return $this->morphedByMany(carrier_manifest::class, 'invoiceable')->withPivot(['amount','rate_id','notes']);
}

public function items(){
    return $this->morphedByMany(InvoiceItems::class, 'invoiceable')->withPivot(['amount','rate_id','notes']);
}

As you can see, in the pivot, I have a table called rate_id. I would like to be able to add a relationship to another model based on the value of the rate_id (the model just being called ChargeRates). Is there a way I can do this in order to access a field in the ChargeRates model called label?

If I have to change up the relationships, what would be the best route to take in my case?

Thanks!

06 Jan
4 months ago

mprythero started a new conversation Sum Of Items Field In Collection Of Collections

I'm trying to see if it's possible, but I would like to get the sum of a field in an item in a collection of collections.

I have the following in my controller:

        $prefiltered_contacts = Contact::with(['donations' => function ($query) use ($request) {
                $query->whereMonth('date_received', $request->month)
                    ->whereYear('date_received', $request->year);
        }])->get();

        $contacts = $prefiltered_contacts ->filter(function ($contact) {
            return $contact->donations->isNotEmpty();
        });

My donation class has the following:

    public function monetary_donations(){
        return $this->hasMany('App\Payments_Distribution', 'donation_id','id');
    }

Now the last part of this is that in the Payments_Distribution class, there is a field titled amount.

If I was coming directly from the Donation model, I would access the sum of the monetary donations as $donation->monetary_donations->sum('amount'); and I would receive the sum. But how would I go about doing this from the Contact model? Or is that even possible given that it would need to go through a collection of donations to get to the collection of monetary_donations? I'm trying to get a report of all Contacts donations (and monetary donations) and output a subtotal of the monetary_donations for that specific period.

If anyone can help, I'd greatly appreciate it!

05 Jan
4 months ago

mprythero started a new conversation Limiting A With?

To be honest, I'm not quite sure where I'm supposed to start with this so if there is any additional clarification needed, feel free to ask.

I have a query on my contactController:

        $contacts = Contact::whereHas('donations', function ($query) use ($request){
                        $query->whereMonth('date_received', $request->month)->whereYear('date_received', $request->year);
                    })->with('donations')->get();

And technically this does work, as it does return all the contacts that had a donation sometime during the month and year period given. But my problem arises when I try to list out the donations as it lists all of that contact's donations. I'd like to only list out the donations that match up with the query above.

At the moment, my blade is like this:

@foreach($contacts as $contact)
{{$contact->surname}}

@foreach($contact->donations as $donation)
{{$donation->id}}
{{$donation->item_id}}
@endforeach

@endforeach

Now I know the above will return all of the donations for that customer, this was merely the format that I would like to have it set up in a report. I know that this type of filtering would likely be somewhere in the controller, so if anyone can help, I'd really appreciate it!

30 Dec
4 months ago

mprythero started a new conversation Call To Undefined Method BinaryFileResponse::header()

I have an issue that appeared after updating the Maatwebsite Laravel Package but they are certain it isn't an issue on their package.

I get the following error: Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header() in my ModifyHeadersMiddleware.php file.

This comes up through the following controller function:

    public function summaryReport(){
        return Excel::download(new ClaimsExport, 'claims-report.xlsx');
    }

Under which my export is as such:

    <?php
    
    namespace App\Exports;
    
    use App\Claim;
    use Maatwebsite\Excel\Concerns\FromView;
    use Maatwebsite\Excel\Concerns\Exportable;
    use Illuminate\Contracts\View\View;
    
    class ClaimsExport implements FromView
    {
        use Exportable;
    
        /**
        * @return \Illuminate\Support\Collection
        */
        public function view(): View
        {
            return view('exports.osd.claims', [
                'claims' => Claim::where('type',2)->where('status',1)->whereNotNull('shipmentID')->orderBy('claimDate','desc')->get()
            ]);
        }
    }

And this is the section of code that is brought up in the ModifyHeadersMiddle.php file:

       public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'      => '*',
            'Access-Control-Allow-Methods'     => 'POST, GET, OPTIONS',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age'           => '86400',
            'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, X-Requested-With'
        ];
 
        if ($request->isMethod('OPTIONS')) {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }
 
        $response = $next($request);
        foreach($headers as $key => $value) {
            $response->header($key, $value);
        }
 
        return $response;
    }

I'd appreciate any help anyone can give. Thank you so much!

26 Dec
5 months ago

mprythero started a new conversation Filtering Polymorphic Relationship

I have the following relationship in a model:

    public function attachments(){
        return $this->morphToMany(ClaimAttachment::class, 'attachable', null, null, 'attachment_id');
    }

Now in the original claim_attachments table (which is referenced through this attachable), I have a column called type. For the most part values include 'jpeg','jpg','pdf','docx' and 'doc'.

I would like to separate the attachments into images and non. What would be the best way to filter them. I'm unsure if it would be filtering down the existing attachments relationship above or what.

I'd appreciate any help anyone can give. Thanks!

25 Dec
5 months ago

mprythero started a new conversation MorphToMany Custom Keys

I'm in the process of trying to convert and clean up a project that had too many tables and classes doing similar functions. I'm going class by class to clean up the code and refresh the functions but one thing I need help with are the custom keys for a morphToMany function.

At the moment, I have a class called osd_detail and it has the following relationship:

public function attachments(){
    return $this->morphToMany(ClaimAttachment::class, 'attachable');
}

And then as you can see I have another class called ClaimAttachment. Well I have an attachables table with the following structure:

  • attachment_id
  • attachable_id
  • attachable_type

But at the moment, when I go to test it out, it still is looking for claim_attachment_id. At the moment, I would prefer to go about changing the foreign key for this instance. I'm not sure I'm quite on the right track and would appreciate any help anyone can give.

Thank you so much!

15 Dec
5 months ago

mprythero started a new conversation Getting Sum Of Field Through Polymorphic Relationship

I have two models, Payments_Distribution and Donation.

In my Donation model:

    public function payments(){
        return $this->morphToMany(Payments_Distribution::class, 'payable');
    }

And I can save a payment distribution to the donation model using the following:

            $distribution = new Payments_Distribution;
            $distribution->payment_id = $payment->id;
            $amount = $request->payment_details['amount'][$i];

            $donation->payments()->save($distribution);

But I'm stuck on how to retrieve the sum of all the associated records' amount fields in the Payment_Distribution model table.

Would it be something like:

$donation->payments()->______ ->sum('amount');

Or something else? I'm still a bit new to polymorphic relationships so I'd appreciate any and all help!

Thanks!

12 Dec
5 months ago

mprythero left a reply on Storage::put - External FTP Site

@jangenent and @lostdreamer_nl - I have finally come across the error again in my work and have the exception returned with it:

ftp_fput(): The process cannot access the file because it is being used by another process.

As I said though, the files are uploaded successfully, so I'm not exactly sure what to do at this moment...

27 Nov
5 months ago

mprythero left a reply on Storage::put - External FTP Site

@jangenent - I'll add the exception message next time it shows now that I've got it inserted into my email. However, I like what I see with your suggestion regarding sentry, so I think I'm going to work on incorporating it into my project as well. Thank you and I'll reply with the exact error message soon.

@lostdreamer_nl - Thanks for your suggestion, I've gone and done that and so now I'll wait and see what the error it is that it produces. Thanks!

mprythero started a new conversation Storage::put - External FTP Site

So I have run across an interesting issue and I am hoping someone might have run across this before or might have some advice for me.

For a project, with each item we get in, we upload an image of a document to an FTP site. At this point in time, it does successfully upload, however every now and then, what I want to call an "imaginary exception" comes up.

My controller action related to this issue is as such:

try{
                    Storage::disk('rrtsdrs-ftp')->put($proN, $file);
                }
                catch (\Exception $e) {
                    $errorMessage = $e->getMessage();

                    Mail::send('emails.response.agentRemitErrors', ['item' => $item], function($message) use ($item){
                        $message->from('*********', '***********');
                        $message->subject('DR Remit Exceptions - '. $item->pro_number);
                        $message->to('*****************');
                    });
                }

I put in this solely to notify me if something goes wonky and I need to reupload an image. However, whenever an exception notifies me, I learn that the image has in fact been successfully uploaded without an issue.

So I'm wondering if there is something else it could be. I'd appreciate any help anyone can provide.

Thanks!

15 Nov
6 months ago

mprythero started a new conversation Upgrade To 5.6 Has Slowed App Considerably

I'm trying to not downgrade as a result, but trying to locate the source of this slowdown is a bit frustrating.

I added Laravel Passport to my project in anticipation of a move where the project was going, but decided to upgrade to 5.6 on my primary Laravel project at the same time.

For some reason though, after the upgrade my load times went from 220ms-3s(for the more complex pages) straight to 11s-41s.

I'm not even sure quite where to start and would appreciate any help anyone could provide. I have significant doubts that it is my database as I can access my largest table and it only takes maybe a quarter of a second to a half second to load (with 46,000 rows).

I have also down the following:

php artisan cache:clear php artisan config:clear php artisan route:clear php artisan view:clear php artisan clear-compilled composer dumpautoload

Does anyone have any additional suggestions? I really would appreciate anything and everything. Thanks!

12 Nov
6 months ago

mprythero left a reply on Laravel Mail Not Sending Attachments Correctly After Update From 5.5 To 5.6

Turns out it's failing even with through a regular mailable as well:

Mail::to($rc)->send(new originRemitManifest($carrier_manifest, $publicPath));

Which still sends out the email correctly, just with the attachment issue again...

mprythero started a new conversation Laravel Mail Not Sending Attachments Correctly After Update From 5.5 To 5.6

I thought I had checked over everything when it came to preparing for an upgrade but now I've run across a strange issue. In the past, this script worked well for me:

                foreach($remitContacts as $rc){
                    $mail = Mail::send('emails.manifests.agentManifests', ['carrier_manifest' => $carrier_manifest], function($message) use ($carrier_manifest,$rc,$storagePath){
                    $message->from('****', '*****');
                    $message->subject('Agent Manifest - '. $carrier_manifest->manifestNumber);
                    $message->to($rc)->cc('******');
                    $message->attach(public_path() . '/' . $storagePath, [
                        'as' => 'manifest.pdf',
                        'mime' => 'application/pdf',
                        ]);
                    });
                }

But now when it sends, the email is correct, but the attachment it sends is nothing more than text added to the body, and looks like below:

--_=swift_1542049002_eb48d1d4f2fa7b2ab6bcd4033bb529d3=_ Content-Type: application/pdf; name=manifest.pdf Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=manifest.pdf JVBERi0xLjUKMSAwIG9iago8PAovQ3JlYXRvciAoKQovQ3JlYXRpb25EYXRlICgyMDE4MTExMjE4 NDAxOCkKL01vZERhdGUgKDIwMTgxMTEyMTg0MDE4KQovQXV0aG9yICgpCi9Qcm9kdWNlciAoKQov VGl0bGUgKCkKL1N1YmplY3QgKCkKL0tleXdvcmRzICgpCj4+CmVuZG9iagoyIDAgb2JqCjw8Ci9U eXBlIC9DYXRhbG9nCi9QYWdlcyAzIDAgUgo+PgplbmRvYmoKMyAwIG9iago8PAovVHlwZSAvUGFn ZXMKL0tpZHMgWzQgMCBSIDEwIDAgUiAxNiAwIFIgXQovQ291bnQgMwovTWVkaWFCb3ggWzAgMCAw IDBdCj4+CmVuZG9iago0IDAgb2JqCjw8Ci9UeXBlIC9QYWdlCi9QYXJlbnQgMyAwIFIKL01lZGlh ....

Does anyone have any suggestions? I wasn't aware this would be affected but apparently was...

Thanks!

05 Nov
6 months ago

mprythero started a new conversation Lockout Screen And JQuery

I was curious if anyone knows of a way to do this or something similar, but I would like to be able to keep an eye on when an authenticated user's session expires and redirect them to the login or a lockout screen.

I'm not sure quite where to start. But my main reason for wanting this is simply because if someone were to fire off an AJAX request and it would fail, the user might not understand why it failed. But I'd like it to just automatically notify and redirect if the session has expired, so that it's one less thing for the user to get tripped up on.

I'm open to any thoughts, I just don't see a straightforward way of doing this... I know it has to exist though, I've been to so many website where they'll either actually close the session in front of me and return me to a login/lockout screen or I'll return and the login/lockout screen has replaced the previous screen.

Thanks!

28 Oct
6 months ago

mprythero started a new conversation OrderBy/sortBy Relationship Using A Fields In A Relationship's Relationship

I have the following relationship in my modal agentBilling:

    public function batches(){
        return $this->hasMany(agent_billings_batches::class,'agentBillingPeriod','id');
    }

And in the agent_billings_batches model, I've got the following relationship:

    public function date(){
            return $this->hasOne(agent_billings_dates::class,'id','dateID');
    }

The agent_billings_dates model has a date fields labeled simply date. Is there a way I could sort the batches relationship in the agentBilling model by the date field in the date relationship of the agent_billings_batches? Or is there a way around this?

Thanks! Matt

10 Oct
7 months ago

mprythero started a new conversation Adding Full URL To Collection Of Files Return

I was playing around with an idea but wanted to check my options, so first I decided to come here.

For example, if you look at the Github API, an example being here: https://api.github.com/search/repositories?q=231

You see that in all of their returns where a url is involved (such as a page or file location) they have the full URL returned. (like this for an item url: https://api.github.com/repos/cthorey/CS231). I was curious if someone thought those were stored in their database or if they were customized in a query or model somewhere.

Just curious, I am trying to find options for me as to on how to code a partner project I am working on.

Thanks! Matt

mprythero started a new conversation Cron Tasks Backend/Frontend Setup

I can't seem to find many examples, or any for that matter, so I was curious to know if anyone had ever setup cron tasks to be handled through a backend database, rather than directly through the console commands. I am interested in setting up like this to provide a little easier of a way to manage tasks that are based on time (such as hourly, daily, weekly, etc.) in a Windows environment where console command execution would be handled by the task scheduler.

I'm just looking for ideas or comments/suggestions, this is down in the planning phase but I want to spend plenty of time making sure I've gone down all avenues.

If anyone has any questions, feel free to send them on my way! Thanks again! Matt

17 Sep
8 months ago

mprythero started a new conversation Eloquent & Conditional Checking

I'm in need of some advice on something I haven't run across before, and while it is a necessary component of a friend's project, I am willing to be flexible in how I should go about it.

In their little museum, they have a staffing and document problem. For several sets of donor types, there are a variety of donor document requirements and what I am trying to do is have the donor type on the donor class reference to many on another table which lays out the required documents of that donor type and what type of required they are (either optional, but recommended or straight up required).

At the moment these are my donor model fields:

id
lastName
firstName
donorType
docStatus

And the relationship to the donorRequiredDocs model is:

public function donorRequiredDocs(){
        return $this->hasMany('App\donorRequiredDocs', 'donorTypeID', 'donorType');
    }

My donorRequiredDocs table is setup as such:

id
donorTypeID
requireType (optional, required)
docType (letter, agreement, etc - but in an INT which references another table)

Now say I have this example:

I am a donor, and my donorType is 1, and 1's are required to have the following documents:

Agreement
Letter of Approval
Notary Required SEM

and are recommended but not required to have:

Photograph of Donation
Statement of Account

And I go to donate an object to the museum, after they select my name and record for the new donation which would use my donor table id to pull up the model information they have on me. I want the the donation record docStatus to remain NULL or 0 until at the very least, the donation record has a relationship with one of each of the three above document types before it can be set to 1.

In this case the donation model is setup as such:

id
title
donorID
public function documents(){
        return $this->hasMany('App\donationAttachment', 'donation_id', 'id');
    }

And the donationAttachment model is setup as such:

id
title
docType (which uses the same numbering system as the `donorRequiredDocs` table field reference)
donation_id
created_at
updated_at

In the end, besides automatically changing the status once the project determines that the donation has at least one of each of the required documents, I'd like to print it out on the blade until all requirements have been met.

If there is something I missed, I'm happy to post it, I'm just not sure about how to go about this and would appreciate any and all help. Thanks in advance.

29 Aug
8 months ago

mprythero left a reply on Laravel - GroupBy As Alias?

Well, I'm not using it through a normal model scope, this is through the DB and I need the alias along with the function, I need the alias for some frontend AJAX. So as much as I'd like that to work, it won't in my case. Thanks - Matt

mprythero started a new conversation Laravel - GroupBy As Alias?

I have the following in one of my functions but would like to refer to it as an alias named Date or give the return a key name, rather than just the formatted date itself:

$loads = $query->get()->groupBy(function($item){
    return Carbon::parse($item->dateTime)->format('F j, Y');
});

This $query starts off as:

$query = DB::table('loads')...

and the field dateTime is a timestamp.

Is there a proper way to do this to include the alias? Thanks!

27 Aug
8 months ago

mprythero started a new conversation Suggestions For Returning JSON Collection From Within Date Collection

I have an interesting request from a friend that I know I've seen examples of around here and there, but am not currently quite sure how to implement it in the controller (or the blade, but I can work on that).

I have a collection of loads currently, which all pulled through this query:

        $query = DB::table('loads')
                  ->leftJoin('shipments', 'loads.shipmentID', '=', 'shipments.id')
                  ->leftJoin('equipment as tractor', 'loads.tractorID', '=', 'tractor.id')
                  ->leftJoin('employees', 'loads.driverID', '=', 'employees.id')
                  ->leftJoin('customers as shipperCustomer', 'shipments.ship_from', '=', 'shipperCustomer.id')
                  ->leftJoin('customers as consigneeCustomer', 'shipments.ship_to', '=', 'consigneeCustomer.id')
                  ->select('loads.id','shipments.pro_number','shipments.id','employees.last_name as driver','tractor.unit_id as tractor','loads.dateTime','shipperCustomer.customer_name as ShipperCustomerName','consigneeCustomer.customer_name as ConsigneeCustomerName','shipments.cn_shipfromName as ShipperName','shipments.cn_shiptoName as ConsigneeName');

        if($request->type){
            $query->where('loads.type', $request->type);
        }

        if($request->status){
            $query->where('loads.status', $request->status);
        }

        $loads = $query->get();

        return response()->json([
                    ['loads'=>$loads],
                    ['time'=>Carbon::now()]
                ]);

And this returns the following response:

[{"loads":[{"id":18296,"pro_number":232231,"driver":"Bettale","tractor":null,"dateTime":"2018-08-27 07:00:00","ShipperCustomerName":"ELECTROLUX HOME PRODUCTS","ConsigneeCustomerName":"LINN STAR","ShipperName":null,"ConsigneeName":null},
{"id":18298,"pro_number":232233,"driver":"Bettale","tractor":null,"dateTime":"2018-08-28 07:00:00","ShipperCustomerName":"ELECTROLUX HOME PRODUCTS","ConsigneeCustomerName":"LINN STAR","ShipperName":null,"ConsigneeName":null},{"id":18297,"pro_number":232232,"driver":null,"tractor":null,"dateTime":"2018-08-27 07:00:00","ShipperCustomerName":"JBS USA\/ GREELEY PLANT","ConsigneeCustomerName":"CONTAINER BUYERS","ShipperName":null,"ConsigneeName":null}]},{"time":{"date":"2018-08-27 11:44:21.304553","timezone_type":3,"timezone":"America\/Denver"}}]

Maybe this is right, I'm not sure at the moment, but what I would, in the end, like is to be able to print out into a table like the following:

-(row 1) August 27, 2018

--(row 2) Load ID: 18296 | Pro Number 232231 --(row 3) Load ID: 18297 | Pro Number 232232

-(row 4) August 28, 2018

--(row 5) Load ID: 18298 | Pro Number 232233

How would one suggest going about this? I am completely open for any suggestions, I've never implemented something like this before and am not even sure quite where to start.

I'd appreciate any help with this!

Thanks - Matt

09 Jul
10 months ago

mprythero started a new conversation Remove GetRouteKeyName From Model

I am in the process of trying to clear up a variety of little aspects of a project I inherited and am in the process of removing the odd Route Key Names from the models. I am testing with the easiest model which had the following in it:

public function getRouteKeyName(){ return 'url_string'; }

I just deleted the lines and saved it but unfortunately it returned "Sorry this page could not be found" when using the regular ID, but brought up successfully using the field contents of url_string.

The route in web.php uses the following: /carrier/customer/show/{customer}

What else do I have to do to remove its dependence on the url_string field?

Thanks! Matt

/UPDATE WITH CONTROLLER METHOD/

public function show(Customer $customer) { return view('customers.show', compact('customer')); }

26 Jun
11 months ago

mprythero left a reply on Return Year Count Even When Count Is 0

I suppose I could but I am not as familiar with array_fill. Could you explain how I would go about implementing it for the zero returned years? Thank you for your suggestion too!

mprythero started a new conversation Return Year Count Even When Count Is 0

I'm trying to work on a chart with a few datasets, however for the purposes of asking this question, I will only include one.

At the moment if I have the following in my controller:

                        ->join('equipment as equip', 'equip.id', '=', 'equipment_attachments.unitID')
                        ->select(DB::raw('year(date) as year'), DB::raw("COUNT(*) as count"))
                        ->where('attachmentCategory','Maintenance')
                        ->where('equip.unit_type',3)
                        ->orderBy(DB::raw("year(date)"))
                        ->groupBy(DB::raw("year(date)"))
                        ->get();````

I will get this returned:

````[{"year":2005,"count":2},{"year":2006,"count":2},{"year":2010,"count":4},{"year":2011,"count":1},{"year":2012,"count":2},{"year":2013,"count":1},{"year":2014,"count":10},{"year":2015,"count":7},{"year":2016,"count":6},{"year":2017,"count":19},{"year":2018,"count":4}]````

As you can see there are a few years missing if I went from say 2000 to the present day. Do you know how I could return the results so that they would come back with the years that have a zero count?

Thanks!

21 May
1 year ago

mprythero started a new conversation Laravel - Generating PDF With Dynamic Image From Storage Stalls

I have an issue with a view and generated content to produce a PDF. At the moment, I've been working with niklasravnsborg\LaravelPdf (a wrapper for mPDF, because of an issue with another PDF writer I was working with beforehand), which turns out nice PDFs that are of the quality that I want.

I have never had an issue with images inside of the view before with this PDF writer though, but I must admit that they were with images that had been set-up inside the view already (like a logo, rather than say an employees photo).

My issue arises in a way that has at least allowed me to track down the issue a little better.

From my controller, I get the following:

$employeeMedCert = $employee->attachments()->where('category','Medical Examiners Certificate')->orderBy('endDate','desc')->limit(1)->get();

And then in my blade I have the following:

        {{Storage::url($med->attachment)}}
 @endforeach```

Now, with this current setup, I get the public path of the attachment, without any issue at all.

HOWEVER, if I do the following:

```@foreach($employeeMedCert as $med){
        <img src="{{Storage::url($med->attachment)}}">
 @endforeach```

It stalls my Laravel to a point where I have to reset the server and hasn't generated anything.

I'm not sure what the issue is, like I said, I've had no issues with images before and the images I am referencing dynamically aren't large by any means (300 - 600 kB), so I am not sure where the issue actually is.

Thanks for the help in advance.

01 Apr
1 year ago

mprythero left a reply on Problem With Multiple Mailings Of Mailable

@Snapey - I kind of figured, at the moment I'm trying to clean up the code but have been a bit overworked on fixing the state of the project all around the place.

I've never broken controller code up before though, this is the only case that I have seen in this project where the controller function stretches to perform more than one task. Do you have any suggestions of where to look for examples for breaking it up properly?

Thank you for your suggestions and comments though, I appreciate them.

31 Mar
1 year ago

mprythero started a new conversation Problem With Multiple Mailings Of Mailable

I have, what appears to me, to be the oddest error and I am hoping someone here can sniff out where my faux pas in my code is.

I have a table of records on a blade, where each record is a row with a checkbox (the name being send[]).

This is not where I am having my issue, but to describe it, when I click a button, it sends off the values of the checkboxes to my controller function, these values are all records values from the default ids in my MySQL table.

NOW, my actual problem lies somewhere in the controller or somewhere I cannot see, but there is an issue that shouldn't be happening no matter what.

This is the function I am referring to:

    {
        $now = Carbon::now();
        $sendNowShipment = array();
        $method = array();
        $sendNowShipment = request('send');
            foreach($sendNowShipment as $SNS){
                $shipment = Shipment::findOrFail($SNS);
                $shipment->billedAt = Carbon::now();
                $shipment->save();
                if($shipment->billtoAccount->billingMethods->label == "Mail"){
                $timestamp = Carbon::now()->timestamp;
                $shipment_details = $shipment->shipment_details;
                    $path = 'temp/freightbill_'.$shipment->pro_number.'-'.$timestamp.'.pdf';
                    $sessionPath[] = $path;
                    $pdf = PDF::loadView('shipments.pdf', compact('shipment', 'shipment_details'))
                        ->save($path);
                }elseif($shipment->billtoAccount->billingMethods->label == "Email"){
                    $billToAccount =   $shipment->billtoAccount;
                    $billToAccountUsers = $billToAccount->users;
                        if ($billToAccount->car_billingEmail){
                            $billToEmail[] = $billToAccount->car_billingEmail;
                        }
                        if ($billToAccountUsers->count() > 0){
                            foreach ($billToAccountUsers as $billToAccountUser){
                                $billToEmail[] = $billToAccountUser->email;
                            }
                        }
                        foreach ($billToEmail as $bte){
                            Mail::to($bte)->send(new newBillToShipment($shipment));
                        }
                }
            }

////////Everything below doesn't appear to affect the issue//////
        $sendShipment = array();
        $method = array();
        $sendShipment = request('send');
            foreach($sendShipment as $ss){
                $shipmentSend = Shipment::findOrFail($ss);
                $method[] = $shipmentSend->billtoAccount->billingMethod;
            }
        
        $counts = array_count_values($method);
        if (array_key_exists(1, $counts)) {
            $countsPrint = $counts[1];
        
        
        if($countsPrint > 0){
            $pdf = new PDFMerger();

            // Add Generated PDFs to the final PDF
            foreach($sessionPath as $sp){
            $pdf->addPDF($sp, 'all');
            }

            // Merge the files and retrieve its PDF binary content
            $timestamp = Carbon::now()->timestamp;
            $binaryContent = $pdf->merge('download', $timestamp."-printBatch.pdf");

            // Return binary content as response
            }
        }
        return back();
    }

To be clear, if the problem is in the function, then it must be between the top of the code and about the middle where I place the note.

Now the problem pops up around this line $shipment->billtoAccount->billingMethods->label == "Email", as it's all focused on the email aspect of this function. If you look through the code, you'll see something about if the billtoAccount has users to pull their emails in as well.

However, this is not the problem. For whatever reason, and I can share screenshots if necessary, I will go through the timeline of events.

I've known about this issue for a while but was only made aware of it after the most recent update I did of Laravel and wonder if it's something there.

I go to click the send now of four (4) records that are email only. Their respective numbers are 9433, 9437, 9438 and 9439.

The button only sends out the one request along with the array of four record ids.

Each one of these belongs to the same account, which has no users included in it, so that portion about the users shouldn't count here and they do have only one billing email (the car_billingEmail field).

After a few seconds, the screen returns back to the original screen.

However, while 8 emails should have been sent out (4 to the customer, one for each invoice, and 4 to me for archival purposes), if I go to Sparkpost (where I handle the emails through), it reports that it sent out about 12 emails.

If I go to my inbox, I see that for two invoices I received one email each, one invoice received two and one received three emails.

Now, given that these are all the same customer, I would've understood receiving the same amount for each invoice (even if it was more than one), but given that the numbers are scattered, I am extremely confused.

What's more is that I know this is not Sparkpost's doing, as I send out other emails through them for other purposes on the site and I don't have these issues.

If you need anymore information or code or whatever, feel free to ask, I'd just really like to fix this issue before I am driven to insanity trying to make sense of it.

Thanks!!!

Matt

29 Mar
1 year ago

mprythero started a new conversation DB::Raw And Order BY

I've having some troubles with a raw statement I'm trying to work out, this portion is in my controller for my home:

                ['unit_type','<',3],
                ['active','=',1]
                        ])
                        ->join(DB::raw('SELECT equipmentID, MAX(expirationDate) AS latest FROM equipment_licenses GROUP BY equipmentID'), 'equipment.id', '=', 'equipment_license.equipmentID')
                        ->orderBy('latest')
                        ->limit(10)
                        ->get();```

The problem is I believe to be the orderBy, but I'm not sure. I keep getting the following error:

```SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT equipmentID, MAX(expirationDate) AS latest FROM equipment_licenses GROUP ' at line 1 (SQL: select * from `equipment` inner join SELECT equipmentID, MAX(expirationDate) AS latest FROM equipment_licenses GROUP BY equipmentID on `equipment`.`id` = `equipment_license`.`equipmentID` where (`unit_type` < 3 and `active` = 1) order by `latest` asc limit 10) ```

I'm not sure how to fix it because the following statement works perfectly for me directly in MySQL Workbench:

```SELECT equipmentID,
MAX(expirationDate) 
AS latest 
FROM equipment_licenses

GROUP BY equipmentID, 'equipment.id', '=', 'equipment_licenses.equipmentID'
ORDER BY latest```

I'd appreciate any help I can get :) Thanks! Matt


13 Mar
1 year ago

mprythero left a reply on Clicking Download Leads To Secure Connection Failed

I'm not sure, I've just been giving it time so it worked, but I'm in Denver, Colorado so maybe a regional thing... I'm not really sure, I'm just glad to be able to work on the videos again haha.

12 Mar
1 year ago

mprythero started a new conversation Clicking Download Leads To Secure Connection Failed

I've been trying to download the videos related to the pusher series (https://laracasts.com/series/get-real-with-laravel-echo/episodes/1) Get Real with Laravel Echo.

And each time I click, it takes me to a page like this: https://player.vimeo.com/external/252759638.hd.mp4?s=f1e557315f83e686b11cf1d95ce610ba2021ac65&profile_id=175&download=1 which says "Secure Connection Failed"

I can't watch the videos either... which is why I needed to download them. Does anyone have any suggestions? I've tried on a few different computers, and made sure to clear caches and try a few different browsers.

Unfortunately they all result in the same...

Thanks - Matt

12 Feb
1 year ago

mprythero left a reply on Laravel-snappy: File Was Not Created

Just as an update, I have reviews the sysinternals process monitor but I don't see anything in related to access denied.

If you look here, someone had a similar question and they posted their sysinternals, but like I said, at the moment I have no mention of access denied.

mprythero left a reply on Laravel-snappy: File Was Not Created

At the moment, I have all options as given full control (to edit, execute, delete, etc), the same goes for the wkhtmltopdf application itself.

At the moment, I'm doing a few tests with sysinternals process monitor and will hopefully be able to post the logs here in a few.

09 Feb
1 year ago

mprythero started a new conversation Laravel-snappy: File Was Not Created

At the moment, I'm trying to trace where this issue arose from given that nothing major was changed.

But at the moment I currently use laravel-snappy to generate pdfs, I haven't had an issue until now when I am all of a sudden receiving the following errors:

    The file 'C:\Users\ADMINI~1\AppData\Local\Temp\knp_snappy5a7d3011c11883.41249127.pdf' was not created (command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf" --lowquality --images --enable-javascript --javascript-delay "10" "C:\Users\ADMINI~1\AppData\Local\Temp\knp_snappy5a7d3011b9a179.91650543.html" "C:\Users\ADMINI~1\AppData\Local\Temp\knp_snappy5a7d3011c11883.41249127.pdf").

Unfortunately, it doesn't tell me why it wasn't created. At this point in time, the error handler points to this specific line where it is returning this error:

    if (!$this->fileExists($output)) {
                throw new \RuntimeException(sprintf(
                    'The file \'%s\' was not created (command: %s).',
                    $output, $command
                ));
            }\

This line comes from this file: vendor\knplabs\knp-snappy\src\Knp\Snappy\AbstractGenerator.php

My wkhtmltopdf binary is located in the correct place, and nothing has changed in response to the setup of these files. And yes, at the moment these files are hosted and served on a Windows Server platform.

My config for the snappy:

    <?php
    
    return array(
    
    
        'pdf' => array(
            'enabled' => true,
            'binary' => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"',
            'timeout' => false,
            'options' => array(),
            'env'     => array(),
        ),
        'image' => array(
            'enabled' => true,
            'binary'  => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage"',
            'timeout' => false,
            'options' => array(),
            'env'     => array(),
        ),
    
    
    );

My files are being generated as such through my controller:

      public function downloadPDF(Shipment $shipment){
                $shipment_details = $shipment->shipment_details;
                 $shipment->print_date = Carbon::now();
                $shipment->save();
          
                $pdf = PDF::loadView('shipments.pdf', compact('shipment','shipment_details'))
                        ->setOption('images', true)
                        ->setOption('enable-javascript', true)
                        ->setOption('javascript-delay', 10);
                return $pdf->download('shipment'.$shipment->uuid.'.pdf');
          
                $shipment->print_date = Carbon::now();
                $shipment->save();
            }

If you have any questions, I'd be incredibly grateful. Best - Matthew

07 Feb
1 year ago

mprythero started a new conversation Laravel Mailable With Attachment Waiting Periods

I haven't run across this before but have had nothing but successes with Laravel Mailable, so I have no true reason to doubt it now. In my application, I have an attachments section to a record. In that section, I give users the options to select attachment that they would like to mail to a email.

My problem is that as of now, using the below current controller, sometimes the send process can take an incredibly long time (at this time, one example was sent only after 3.67 minutes !!). I understand that this might be partially because of the size, but I'm concerned about this timing and would like to see if there might be a backend alternative (such as queue).

At the moment here is my controller for the command to send to the mailable:

    public function attachmentsEmail(Request $request){
            $shipment = Shipment::findOrFail($request->shipmentID);
            $attachment = Shipment_Attachment::findOrFail($request->attachmentID);
            $storagePath = Storage::url($attachment->attachmentPath);
            $customMessage = $request->customMessage;
            $email = $request->email;
            
                 Mail::to($email)->send(new shipmentAttachments($shipment, $attachment, $storagePath, $customMessage));  //maybe try to use queue instead of send...        
            return response()->json([
                                        'shipment' => $shipment,
                                        'customMessage' => $customMessage,
                                        'email' => $email
                                    ]);
        }

We are currently using Windows Server, so while I would like to use queue, I cannot use supervisor to maintain my queues.

However, if there are other suggestions, I'm willing to take them. I'm still relatively new at this and understand that there may be better ways of handling these issues.

Thanks - Matt

01 Feb
1 year ago

mprythero started a new conversation Mailiable Queue Supervisor Advice

I was curious if anyone has run Laravel on a Windows environment and used a Supervisor alternative of sorts.

I'm stuck with the current equipment our non-profit uses and there are a few mailables that have issues consistently sending rapidly and will hang on the front end.

So rather, I was suggested to look into queuing my mailables rather than sending them outright right away.

But it looks like the Supervisor suggested is only for Linux, and so while I'd love to start using queue, I'm concerned it might get stuck, fail and not get reenabled to listen again.

I'd love any advice anyone can provide, I'd certainly appreciate everything.

Best - Matt

mprythero started a new conversation Laravel - Unable To Open File For Reading / Swift_IoException

IN trying to use mailable in Laravel, I have run into an issue that I haven't come across before and it appears nothing currently out there can help.

In developing a new mailable, I have everything working except attaching an EXISTING file to the mailable.

An error returns as such:

       "message": "Unable to open file for reading [/public/storage/shipments/CJ2K4u6S6uluEGd8spOdYgwNkg8NgLFoC6cF6fm5.pdf]",
        "exception": "Swift_IoException",
        "file": "E:\webserver\htdocs\truckin\vendor\swiftmailer\swiftmailer\lib\classes\Swift\ByteStream\FileByteStream.php",
        "line": 131,

But if you go through the folders and files, there is in fact a file there and I can open it, I can even open it through an ajax popup to view details.

Here is my mailable:

    <?php
    
    namespace App\Mail;
    
    use Illuminate\Bus\Queueable;
    use Illuminate\Mail\Mailable;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    use App\Shipment;
    use App\Shipment_Attachment;
    
    class shipmentAttachments extends Mailable
    {
        use Queueable, SerializesModels;
    
        /**
         * Create a new message instance.
         *
         * @return void
         */
        public $shipment, $attachment, $storagePath;
        
        public function __construct($shipment, $attachment, $storagePath)
        {
            $this->shipment = $shipment;
            $this->attachment = $attachment;
            $this->attachmentFile = '/public'.$storagePath;
            $this->proNumber = $shipment->pro_number;
        }
    
        /**
         * Build the message.
         *
         * @return $this
         */
        public function build()
        {
             return $this->from('[email protected]')
                        ->cc('[email protected]')
                        ->subject('New Attachment(s) - '. $this->proNumber)
                        ->view('emails.shipments.shipmentAttachments',['shipment'=> $this->shipment])
                        ->attach($this->attachmentFile);
        }
    }

And here is my controller that leads to the mailable:

    public function attachmentsEmail(Request $request){
            $shipment = Shipment::findOrFail($request->shipmentID);
            $attachment = Shipment_Attachment::findOrFail($request->attachmentID);
            $storagePath = Storage::url($attachment->attachmentPath);
            $email = $request->email;
            
                 Mail::to($email)->send(new shipmentAttachments($shipment, $attachment, $storagePath));  //maybe try to use queue instead of send...        
            return back();
        }

So I'm not sure where this could be coming up from, I feel it must be simple but I'm not sure how it could be fixed. Thanks - Matt

26 Jan
1 year ago

mprythero left a reply on Laravel - Posting To Array Error

This is my new script to add a row (and in turn a new shipment_detail:

<script>
 $(document).ready(function(){  
      var i=1;  
      $('#add').click(function(){  
            i++;  
           $('#freight_bill_items').append('<tr id="row'+i+'"><td style="width:8%;text-align:center;"><input type="text" id="piecesNumber" class="form-control" placeholder="No. Pieces" required name="shipment_details[][piecesNumber]">          </td><td style="width:16%;text-align:center;"><select id="pieces_type" class="form-control full-width" required name="shipment_details[][piecesType]">              @foreach($cPiecetypes as $cPt)<option value="{{$cPt->id}}">{{$cPt->label}}</option> @endforeach</select></td><td><select id="pieces_type" class="form-control full-width" required name="shipment_details[][rateType]">@foreach($cRatetypes as $cRt)<option value="{{$cRt->id}}">{{$cRt->label}}</option>@endforeach</select></td>        <td style="width:16.5%;text-align:center;"><input type="text" id="weight" class="form-control" placeholder="Weight" required name="shipment_details[][weight]"></td><td style="width:16.5%;text-align:center;"><select id="hazmat" class="form-control full-width" required name="shipment_details[][hazmat]"><option value="0">No</option><option value="1">Yes</option></select></td><td style="width:16.5%;text-align:center;">      <input type="text" id="description" class="form-control" placeholder="Description" required name="shipment_details[][description]"></td><td style="width:16.5%;text-align:center;"><input type="text" id="charge" class="form-control" placeholder="Charge" required name="shipment_details[][charge]"></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');   
      });  
      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();
           $( 'input[name^="shipment_details[charge][]"]' ).trigger( "change" );
      });
     
 });
</script>

and this is how the existing shipment_details are placed in the edit form:

<tbody>
                    @foreach($shipment_details as $sd)
                        <tr style="height:40px">
                            <td style="width:8%;text-align:center;">
                            <input type="text" id="piecesNumber" class="form-control" placeholder="No. Pieces" required name="shipment_details['.$sd->id.'][piecesNumber]" value="{{$sd->pieces_number}}">
                            </td>
                            <td style="width:16%;text-align:center;">
                            <select id="pieces_type" class="form-control full-width" required name="shipment_details['.$sd->id.'][piecesType]">
                                @foreach($cPiecetypes as $cPt)
                                    <option value="{{$cPt->id}}"
                                     @if ($sd->pieces_type == $cPt->id) selected="selected" 
                                     @endif>{{$cPt->label}}</option>
                                @endforeach
                                
                            </select>    
                            </td>
                            <td>
                             <select id="pieces_type" class="form-control full-width" required name="shipment_details['.$sd->id.'][rateType]">
                                @foreach($cRatetypes as $cRt)
                                    <option value="{{$cRt->id}}"
                                     @if ($sd->rate_type == $cRt->id) selected="selected" 
                                     @endif>{{$cRt->label}}</option>
                                @endforeach
                                
                            </select>
    
                            </td>
                            <td style="width:16.5%;text-align:center;">
                            <input type="text" id="weight" class="form-control" placeholder="Weight" required name="shipment_details['.$sd->id.'][weight]" value="{{$sd->weight}}">
                               
                            </td>
                            <td style="width:16.5%;text-align:center;">
                            
                            <select id="hazmat" class="form-control full-width" required name="shipment_details['.$sd->id.'][hazmat]">
                     
                                    <option value="0"
                                     @if ($sd->hazmat = 0) selected="selected" 
                                     @endif>No</option>
                                     <option value="1"
                                     @if ($sd->hazmat = 1) selected="selected" 
                                     @endif>Yes</option>
                                
                            </select>
                             
                            </td>
                            <td style="width:16.5%;text-align:center;">
                            <input type="text" id="description" class="form-control" placeholder="Description" required name="shipment_details['.$sd->id.'][description]" value="{{$sd->description}}">
                            
                            </td>
                            <td style="width:16.5%;text-align:center;">
                            <input type="text" id="charge" class="form-control" placeholder="Charge" required name="shipment_details['.$sd->id.'][charge]" value="{{$sd->charge}}">
                            </td>
                            <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                </tr>
                    
                    @endforeach
            </tbody>

Thanks! Matt

mprythero left a reply on Laravel - Posting To Array Error

I'll post the updated forms but outright I get the error, cannot use [] for reading and it references the updated portion you suggested:

foreach ($request->shipment_details as $id => $details) {
                $shipdetail = Shipment_Detail::updateOrCreate(['id' => $id], [
                'pieces_type' => $details[]['piecesType'],
                'pieces_number' => $details[]['piecesNumber'],
                'rate_type' => $details[]['rateType'],
                'weight' => $details[]['weight'],
                'charge' => $details[]['charge'],
                'description' => $details[]['description'],
                'hazmat' => $details[]['hazmat']
                    ]);
            }

mprythero left a reply on Laravel - Posting To Array Error

@Snapey - That's fine, it's an older form I have to update anyways. So I'll do that, and come back with an updated form for you. And I do understand, so I'll be back! Thanks

mprythero started a new conversation Laravel - Posting To Array Error

I have an edit form for a model and a section is dedicated to that specific record's child records called "shipment_details".

Since editing a record will always show at least one existing shipment_detail record, this form section looks like: At the moment my html of the "shipment_details" is as such from the blade:

    <tbody>
        @foreach($shipment_details as $sd)
        <tr style="height:40px">
            <td style="width:8%;text-align:center;">{{Form::text('shipment_details['.$sd->id.'][piecesNumber]', $sd->pieces_number, array('class' => 'form-control','placeholder'=>'No. Pieces','required','id'=>'piecesNumber'))}}
            </td>
            <td style="width:16%;text-align:center;">
                {!! Form::select('shipment_details['.$sd->id.'][piecesType]', $piecetypes, $sd->pieces_type, ['id' => 'pieces_type', 'class' => 'form-control full-width','required']) !!}    
            </td>
            <td>
                {!! Form::select('shipment_details['.$sd->id.'][rateType]', $ratetypes, $sd->rate_type, ['id' => 'rateType', 'class' => 'form-control full-width','required']) !!}
            </td>
            <td style="width:16.5%;text-align:center;">
                {{Form::text('shipment_details['.$sd->id.'][weight]', $sd->weight, array('class' => 'form-control','placeholder'=>'Weight','required','id'=>'weight'))}}    
            </td>
            <td style="width:16.5%;text-align:center;">
                {{Form::select('shipment_details['.$sd->id.'][hazmat]',array(
                                        '0'=>'No',
                                        '1'=>'Yes',
                                    ), $sd->hazmat, array('class' => 'form-control','id'=>'hazmat'))}}   
            </td>
            <td style="width:16.5%;text-align:center;">
                                {{Form::text('shipment_details['.$sd->id.'][description]', $sd->description, array('class' => 'form-control','placeholder'=>'Description','required','id'=>'description'))}} 
            </td>
            <td style="width:16.5%;text-align:center;">
                {{Form::text('shipment_details['.$sd->id.'][charge]', $sd->charge, array('class' => 'form-control','placeholder'=>'Charge','required','id'=>'charge'))}} 
            </td>
            <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
        </tr>
                        
        @endforeach
    </tbody>

But if there is a need to add additional shipment_details, I have a script which adds additional record rows formatted below:

    <script>
     $(document).ready(function(){  
          var i=1;  
          $('#add').click(function(){  
                i++;  
               $('#freight_bill_items').append('<tr id="row'+i+'"> <td style="width:8%;text-align:center;">{{Form::text('shipment_details[piecesNumber][]', null, array('class' => 'form-control','placeholder'=>'No. Pieces','required','id'=>'piecesNumber'))}}</td><td style="width:16%;text-align:center;">{!! Form::select('shipment_details[piecesType][]', $piecetypes, 'null', ['id' => 'pieces_type', 'class' => 'form-control full-width','required']) !!} </td><td>{!! Form::select('shipment_details[rateType][]', $ratetypes, null, ['id' => 'rateType', 'class' => 'form-control full-width','required']) !!}</td><td style="width:16.5%;text-align:center;">{{Form::text('shipment_details[weight][]', null, array('class' => 'form-control','placeholder'=>'Weight','required','id'=>'weight'))}}</td><td style="width:16.5%;text-align:center;">{{Form::select('shipment_details[hazmat][]',array('No'=>'No','Yes'=>'Yes',), null, array('class' => 'form-control','id'=>'hazmat'))}}</td><td style="width:16.5%;text-align:center;">{{Form::text('shipment_details[description][]', null, array('class' => 'form-control','placeholder'=>'Description','required','id'=>'description'))}}</td><td style="width:16.5%;text-align:center;">{{Form::text('shipment_details[charge][]', null, array('class' => 'form-control','placeholder'=>'Charge','required','id'=>'charge'))}}</td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');   
          });  
          $(document).on('click', '.btn_remove', function(){  
               var button_id = $(this).attr("id");   
               $('#row'+button_id+'').remove();
               $( 'input[name^="shipment_details[charge][]"]' ).trigger( "change" );
          });
         
     });
    </script>

My problem arises when I go to post the data, the existing data is "arrayed" correctly, but the new data isn't and at the moment gives me an undefined index record.

Here is the current POST data output for shipment_details for a test record:

  shipment_details  
    
    array:8 [▼
      13149 => array:7 [▼
        "piecesNumber" => "1"
        "piecesType" => "1"
        "rateType" => "1"
        "weight" => "12"
        "hazmat" => "0"
        "description" => "124"
        "charge" => "12.00"
      ]
      "piecesNumber" => array:1 [▼
        0 => "3"
      ]
      "piecesType" => array:1 [▼
        0 => "2"
      ]
      "rateType" => array:1 [▼
        0 => "2"
      ]
      "weight" => array:1 [▼
        0 => "1200"
      ]
      "hazmat" => array:1 [▼
        0 => "Yes"
      ]
      "description" => array:1 [▼
        0 => "desc2"
      ]
      "charge" => array:1 [▼
        0 => "40.00"
      ]
    ]

So as you can see, the inputs are all separate except for the existing record, so my problem must be originating in my form. Does anyone have any suggestions?

This is how it should be sent (or in a similar format, I believe):

      13149 => array:7 [▼
        "piecesNumber" => "1"
        "piecesType" => "1"
        "rateType" => "1"
        "weight" => "12"
        "hazmat" => "0"
        "description" => "124"
        "charge" => "12.00"
      ]

Since the new records don't have a record ID assigned yet, I don't believe the top row would be the same for the new records but this should explain my request.

Portion of Controller with Section about shipment_detail

    foreach ($request->shipment_details as $id => $details) {
                $shipdetail = Shipment_Detail::updateOrCreate(['id' => $id], [
                'pieces_type' => $details['piecesType'][0],
                'pieces_number' => $details['piecesNumber'][0],
                'rate_type' => $details['rateType'][0],
                'weight' => $details['weight'][0],
                'charge' => $details['charge'][0],
                'description' => $details['description'][0],
                'hazmat' => $details['hazmat'][0]
                    ]);
            }

Thanks - Matt

09 Jan
1 year ago

mprythero started a new conversation Count Array Where Column Value Equals Given

I have a controller where an array of checkbox values are passed on to the controller and then sent on to do a variety of tasks. My problem is focused on getting a count of the arrays' shipment's customer's billing method, but I'm not entirely sure how I would get those values since I'm posting an array and I want a count.

Here's my controller:

    public function sendNow(Request $request)
        {
            $now = Carbon::now();
            $sendNowShipment = array();
            $method = array();
            $sendNowShipment = request('send');
                foreach($sendNowShipment as $SNS){
                    $shipment = Shipment::findOrFail($SNS);
                    if($shipment->billtoAccount->billingMethods->label == "Mail"){
                    $timestamp = Carbon::now()->timestamp;
                    $shipment_details = $shipment->shipment_details;
                        $path = 'temp/freightbill_'.$shipment->pro_number.'-'.$timestamp.'.pdf';
                        $sessionPath[] = $path;
                        $pdf = PDF::loadView('shipments.pdf', compact('shipment', 'shipment_details'))
                            ->save($path);
                    }elseif($shipment->billtoAccount->billingMethods->label == "Email"){
                        $billToAccount =   $shipment->billtoAccount;
                        $billToAccountUsers = $billToAccount->users;
                            if ($billToAccount->primary_email){
                                $billToEmail[] = $billToAccount->primary_email;
                            }
                            if ($billToAccountUsers->count() > 0){
                                foreach ($billToAccountUsers as $billToAccountUser){
                                    $billToEmail[] = $billToAccountUser->email;
                                }
                            }
                            foreach ($billToEmail as $bte){
                                Mail::to($bte)->send(new newBillToShipment($shipment));
                            }
                    }
                }
            
            if(count($shipment->billtoAccount->billingMethods->label == "Mail") > 0){// count where shipments->customers->billingMethods = Mail) > 0
                $pdf = new PDFMerger();
    
                // Add 2 PDFs to the final PDF
                foreach($sessionPath as $sp){
                $pdf->addPDF($sp, 'all');
                }
    
                // Merge the files and retrieve its PDF binary content
                $timestamp = Carbon::now()->timestamp;
                $binaryContent = $pdf->merge('download', $timestamp."-printBatch.pdf");
    
                // Return binary content as response
                //return response($binaryContent)
                  //  ->header('Content-type' , 'application/pdf');
                return back();
                //dd($sendNowShipment,$sendMethod);
        }
        }

If you look at this line (a little past the middle):

    if(count($shipment->billtoAccount->billingMethods->label == "Mail") > 0){
    // count where shipments->customers->billingMethods = Mail) > 0

You'll see that I'm going through a multitude of relationships just to get the value of "Mail" that I am looking for.

So I'm wondering if this should be a DB:: query through laravel, but I'm not sure how I would perform the query using the given checkbox array I have being POSTed to this controller.

03 Jan
1 year ago

mprythero started a new conversation Creating A Recently Viewed Pages/Model IDs List

This may seem like a very broad question, but I haven't found a proper way around it. Is there a proper way I should go about storing and retrieving a list of recent pages a user has visited (I'd only intend to keep about 10 pages per session), but I'd like to record every page visited so a user could rapidly return to a page at some point if they so chose.

There are many models that run across the site I'm working on, and a few hundred pages, so if anyone has any suggestions, I'd certainly appreciate them.

Best -

Matt

02 Jan
1 year ago

mprythero started a new conversation Laravel Uploading File - Creating Default Object From Empty Value

I seem to be getting an error in what I assume is in relation to me uploading a file.

Here is my controller:

    public function scannerUpload(Request $request){
        $requestFile = request('RemoteFile');
        $path = Storage::putFile('public/shipments', new File(request('RemoteFile')));
            Shipment_Attachment::create([
                             $Shipment_Attachment->attachmentPath = $path,
                             $Shipment_Attachment->attachmentBody = request('Description'),
                             $Shipment_Attachment->attachmentVisibility = request('Visibility'),
                             $Shipment_Attachment->attachmentDate = request('Date'),
                             $Shipment_Attachment->attachmentType = request('Type'),
                             $Shipment_Attachment->attachmentLong = request('Longitude'),
                             $Shipment_Attachment->attachmentLat = request('Latitude'),
                             $Shipment_Attachment->shipment_id = request('ShipmentID'),
                             $Shipment_Attachment->user_id =>  Auth::id()
                        ]);  
        return response()->json($request);
        }

Now I get an error at this line: $Shipment_Attachment->attachmentPath = $path, with the following: Creating default object from empty value.

But I'm wondering if maybe I'm not uploading and requesting the file correctly. When I post the file, this is what the parameters look like after I click my upload button:

    -----------------------------54701348911009
    Content-Disposition: form-data; name="Date"
    
    2018-01-02
    -----------------------------54701348911009
    Content-Disposition: form-data; name="Visibility"
    
    1
    -----------------------------54701348911009
    Content-Disposition: form-data; name="Type"
    
    1
    -----------------------------54701348911009
    Content-Disposition: form-data; name="Description"
    
    This is a Description
    -----------------------------54701348911009
    Content-Disposition: form-data; name="Latitude"
    
    39.777541
    -----------------------------54701348911009
    Content-Disposition: form-data; name="Longitude"
    
    -104.94250199999999
    -----------------------------54701348911009
    Content-Disposition: form-data; name="shipmentID"
    
    32109829
    -----------------------------54701348911009
    Content-Disposition: form-data; name="RemoteFile"; filename="test-pod.pdf"
    Content-Type: application/octet-stream
    
    %PDF-1.5
    1 0 obj
    <<
    /Creator ()
    /CreationDate (20180102192642)
    /ModDate (20180102192642)
    /Author ()
    /Producer () and so on and so on for another hundred lines

So am I correct in how I am handling the upload of the file or should it be handled differently?

Thanks! Matt

30 Dec
1 year ago

mprythero started a new conversation Laravel & Twain Upload Controller Connection

Out of curiosity, I was wondering if anyone has run into a situation similar to this. I am trying to incorporate a web twain into my laravel project, but how it posts the data for the upload is a little odd to me as I haven't ever seen something like it before.

If I'm posting and I take a look at the POST parameters, I see this:


-----------------------------23491353817351
Content-Disposition: form-data; name="This is a field"

Wow
-----------------------------23491353817351
Content-Disposition: form-data; name="RemoteFile"; filename="507-0.jpg"
Content-Type: application/octet-stream

ÿØÿà ...... and a looooot of jarbled code here (you'll see in the example)

and so on and so on. You can see the basic example here: https://demo.dynamsoft.com/Samples/dwt/Scan-Documents-and-Upload-Them/DWT_Scan_Upload_Demo.html

or a more complex example here: https://demo.dynamsoft.com/dwt/online_demo_scan.aspx

It's published as working well with php and I have it working in my project separately, but don't quite understand how I might form the controller to accept this form of upload.

If you have any suggestions around working with this, or even another suggestion for a web twain, I'd certainly appreciate any help anyone can give.

Thanks so much in advance - Best - Matt

28 Dec
1 year ago

mprythero left a reply on AJAX - Post Table Rows And Individual Inputs

@lostdreamer_nl - I'll look into the serialization. Out of curiosity, should my script now look like this?


        $(document).on('click', '.createPayment', function() {
            $('.modal-title').text('Record New Payment');
            $('#payment').modal('show');
        });
        $('.modal-footer').on('click', '.add_payment', function() {
            //ERROR COULD BE BELOW HERE//
            var shipments = [];
            var amounts = [];
            var payment_details = [];
            $("input[name='payment_details[shipment_id][]']").each(function(){
                    shipments.push(this.value);
                });
            $("input[name='payment_details[amount][]']").each(function(){
                    amounts.push(this.value);
                });
            for (i = 0; i < shipment_ids.length; i++) { 
                    payment_details[] = {
                        shipment_id: shipments[i],
                        amount: amounts[i],
                    };
                }
            //OR ERROR COULD BE UP ABOVE HERE//
            $.ajax({
            type:'POST',
            url: '/payments/createNew',
            data: {
                payer_id: $('select[name=payer_id]').val(),
                notes: $('input[name=notes]').val(),
                payment_amount: $('input[name=payment_amount]').val(),
                date_deposit: $('input[name=date_deposit]').val(),
                check_number: $('input[name=check_number]').val(),
                deposit_type: $('select[name=deposit_type]').val(),
                _token: $('input[name=_token]').val(),
            },
                success: function(data) {
                    $('.errorTitle').addClass('hidden');
                    $('.errorContent').addClass('hidden');

                    if ((data.errors)) {
                        setTimeout(function () {
                            $('#payment').modal('show');
                            toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
                        }, 500);

                        if (data.errors.title) {
                            $('.errorTitle').removeClass('hidden');
                            $('.errorTitle').text(data.errors.title);
                        }
                        if (data.errors.content) {
                            $('.errorContent').removeClass('hidden');
                            $('.errorContent').text(data.errors.content);
                        }
                    } else {
                        toastr.success('Successfully recorded Payment!', 'Success Alert', {timeOut: 5000});

                    }
                },
            });
        });

It's not working but while I try and skirt through the code using JSHint and other forums, I was hoping you might see something if it's as obvious as I think it is. And thank you for all of your help!

mprythero started a new conversation AJAX - Post Table Rows And Individual Inputs

I have a project in Laravel that I am working on and one portion requires me to work with submitting a form through a modal, the problem is I'm not as familiar with AJAX as I'd like to be and I've run into an issue.

Here are the modal contents:

    <table>
            <tr>
            <td>
                {{ csrf_field() }}
                <select name="payer_id" class="js-basic-single payer_id" style="width:100%;" id="payer_id">
                     <option></option>
                     @foreach($customers as $customer)
                     <option value="{{ $customer->id }}">{{ $customer->customer_name }}</option>
                     @endforeach
                </select>
                <div id="existing_biller_details" class="hidden" name="existing_biller_details" style="margin-top:10px;">
                    </div>
                <select class="form-control deposit_type" name="deposit_type" id="deposit_type">
                <option disabled selected>Please Select</option>
                <option value="Check">Check</option>
                <option value="Cash">Cash</option>
                    <option value="ECheck">ECheck</option>
                </select>
                <div name="check_number" id="check_number" class="hidden">
                      <input type="text" placeholder="Check Number" class="form-control" id="check_number" name="check_number">
                  </div>
                <input type="text" class="form-control" placeholder="Payment Amount" name="payment_amount" id="payment_amount">
                <input type="date" class="form-control" placeholder="Date of Deposit" name="date_deposit" id="date_deposit">
                <textarea placeholder="Notes" style="width:100%;" class="form-control" id="notes" name="notes"></textarea>
            </td><td style="width:50%;">
                <table style="width:100%;" id="freight_bill_items">
                    <thead>
                    
                        <td style="width:30%;font-weight:bold;text-align:center;">Bill No.</td><td style="width:30%; font-weight:bold; text-align:center;">Amount</td>
                        
                    </thead>
                    <tbody>
                        <tr style="height:40px">
                    <td style="width:30%;text-align:center;"><input type="text" name="payment_details[shipment_id][]" required class="form-control name_list" id="shipment_id" placeholder="Bill No." required></td><td style="width:30%;text-align:center;"><input type="text" name="payment_details[amount][]" required class="form-control name_list" id="amount" placeholder="Amount" required>
                            </td><td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                    </tr>
                </tbody>
                </table>
                    <div id="freight_bill_items_subtotal;" style="font-weight:bold; padding-top:10px; padding-bottom:10px; text-align:left; background-color: #f0f8ff;">
                    SUBTOTAL:
                        <input type="text" readonly name="freightBillSubtotal" id="freightBillSubtotal" class="form-control total_field" style="display:inline;" value="0.00">
                    </div>
                
                
                
                
                </td>    
            </tr>
            </table>

As you can see a little bit lower, there is a div called "freight_bill_items", with a table and in the only tbody row, the two text inputs and a button to add another table row with the same exact inputs.

Now here at the moment is my ajax script:

    <script type="text/javascript">
            $(document).on('click', '.createPayment', function() {
                $('.modal-title').text('Record New Payment');
                $('#payment').modal('show');
            });
        $('.modal-footer').on('click', '.add_payment', function() {
            //ERROR COULD BE BELOW HERE//
            var payment_details = [];
            $("input[name='payment_details[shipment_id][]']").each(function(){
                    payment_details.push(this.value);
                });
            $("input[name='payment_details[amount][]']").each(function(){
                    payment_details.push(this.value);
                });
            
            //OR ERROR COULD BE UP ABOVE HERE//
            $.ajax({
                type:'POST',
                url: '/payments/createNew',
                data: {
                    payer_id: $('input[name=payer_id]').val(),
                    notes: $('input[name=notes]').val(),
                    payment_amount: $('input[name=payment_amount]').val(),
                    date_deposit: $('input[name=date_deposit]').val(),
                    check_number: $('input[name=check_number]').val(),
                    deposit_type: $('input[name=deposit_type]').val(),
                    payment_details:payment_details, //LOOKING FOR ASSISTANCE HERE//
                    _token: $('input[name=_token]').val(),
                },
                    success: function(data) {
                        $('.errorTitle').addClass('hidden');
                        $('.errorContent').addClass('hidden');
    
                        if ((data.errors)) {
                            setTimeout(function () {
                                $('#payment').modal('show');
                                toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
                            }, 500);
    
                            if (data.errors.title) {
                                $('.errorTitle').removeClass('hidden');
                                $('.errorTitle').text(data.errors.title);
                            }
                            if (data.errors.content) {
                                $('.errorContent').removeClass('hidden');
                                $('.errorContent').text(data.errors.content);
                            }
                        } else {
                            toastr.success('Successfully recorded Payment!', 'Success Alert', {timeOut: 5000});
    
                        }
                    },
                });
            });
    </script>

Now what I'm stuck on is how do I pass these rows and their input contents into arrays to POST along with the other values?

At the moment, with the above code, I get the following as the parameters:

payment_amount  143.00
date_deposit    2017-12-28
check_number    41504
payment_details[]   […]
0   214267
1   214276
2   71.50
3   71.50
_token  E669......

My issue is that I need it to be like this for the payment_details[] 0 -> shipment_id => 214267 -> amount => 71.50

1 ->shipment_id => 214276 ->amount => 71.50

I'd appreciate any help anyone can provide, and much thanks in advance -

Best - Matt

25 Dec
1 year ago

mprythero started a new conversation Laravel - WHERE Clause With Relationship To Another Table (DB::raw??)

I've got a couple of tables in my Laravel application, one called shipments and the other called payments_distributions.

In my shipments, I have columns called pro_number and balance.

In my payments_distributions I have columns called shipment_id and amount.

Now I have a controller which has this portion of code in it:

    }elseif($_GET['paymentStatus']=="Unpaid"){
        if(empty($_GET['pro_number'])){
                $shipment = NULL;
            }else{
            $shipment = $_GET['pro_number'];
            }
            
            if($_GET['startDate']){
                $startDate = $_GET['startDate'];
            }
            if($_GET['endDate']){
                $endDate = $_GET['endDate'];
            }
                    $start = $_GET['startDate'];
                    $end = $_GET['endDate'];
                    $status = $_GET['paymentStatus'];
        $date = \Carbon\Carbon::today()->subDays(0);
    
        $shipments = Shipment::sortable()
        ->where([
            ['due_date','<=',date($date)],
            ['pro_number', 'LIKE', '%' . $shipment . '%'],
            ['balance','>','SELECT SUM(payments_distributions.amount) FROM payments_distributions WHERE payments_distributions.shipment_id = pro_number'],
        ])
        ->whereBetween('date', [$startDate, $endDate])
        ->whereNotIn('shipment_billing_status', [2,3])
        ->paginate(25);
        return view('shipments.accounts', compact('shipments','start','end','status'));
        
    }

Now my issue arises in that the following code works if I put it into MYSQL:

    SELECT SUM(payments_distributions.amount) FROM payments_distributions WHERE payments_distributions.shipment_id = 214050

Will return SUM(payments_distributions.amount): 300.00

So, if you go to the line in my code, this is the only thing that doesn't work, so if you could, does this line of code look right to everyone? All I'm trying to say that the balance field from a shipment row must be larger than the sum of amount fields in the payment_distributions table where the shipment_id field in the payment_distributions table equals the pro_number field in the shipments table.

     ['balance','>',DB::raw('SELECT SUM(payments_distributions.amount) FROM payments_distributions WHERE payments_distributions.shipment_id = pro_number')],
        ]

My full error in fact is:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT SUM(p.amount) FROM payments_distributions p WHERE p.shipment_id = shipmen' at line 1 (SQL: select count(*) as aggregate from `shipments` where (`due_date` <= 2017-12-26 00:00:00 and `pro_number` LIKE %% and `balance` > SELECT SUM(p.amount) FROM payments_distributions p WHERE p.shipment_id = shipments.pro_number) and `date` between 1997-12-01 and 2017-12-25 and `shipment_billing_status` not in (2, 3))

And I will point this out, everything else works, it's just this balance issue that is causing the problems.

Thank you so much for all of the help in advance, I greatly appreciate it!

Thanks! Matthew

----UPDATE (THE ENTIRE FUNCTION) ------

public function accountsQuery(){
        

if(($_GET['paymentStatus'] == "No Settle") or ($_GET['paymentStatus'] == "No Charge")){
            if($_GET['paymentStatus'] == "No Settle"){
                $status = 3;
            }elseif($_GET['paymentStatus'] == "No Charge"){
                $status = 2;
            }
                if(empty($_GET['pro_number'])){
                $shipment = NULL;
                }else{
                $shipment = $_GET['pro_number'];
                }

                if($_GET['startDate']){
                    $startDate = $_GET['startDate'];
                }
                if($_GET['endDate']){
                    $endDate = $_GET['endDate'];
                }
                        $start = $_GET['startDate'];
                        $end = $_GET['endDate'];
                        $status = $_GET['paymentStatus'];
                        $shipments = \App\Shipment::sortable()->where([ 
                            ['pro_number', 'LIKE', '%' . $shipment . '%'],
                            ['shipment_billing_status', 'LIKE', '%' . $status . '%'],
                        ])
                            ->whereBetween('date', [$startDate, $endDate])
                            ->paginate(25);
                return view('shipments.accounts', compact('shipments','start','end','status'));
    
}elseif($_GET['paymentStatus']=="Billed"){
    if(empty($_GET['pro_number'])){
            $shipment = NULL;
        }else{
        $shipment = $_GET['pro_number'];
        }
        
        if($_GET['startDate']){
            $startDate = $_GET['startDate'];
        }
        if($_GET['endDate']){
            $endDate = $_GET['endDate'];
        }
                $start = $_GET['startDate'];
                $end = $_GET['endDate'];
                $status = $_GET['paymentStatus'];
    $date = \Carbon\Carbon::today()->subDays(30);
    //AND TO MENTION WHERE SUM OF PAYMENTS TO THIS SHIPMENT < BALANCE DUE
    $shipments = Shipment::sortable()
    ->where([
        ['date','>=', date($date)],
        ['pro_number', 'LIKE', '%' . $shipment . '%'],
    ])
    ->whereBetween('date', [$startDate, $endDate])
    ->paginate(25);
    return view('shipments.accounts', compact('shipments','start','end','status'));
    
}elseif($_GET['paymentStatus']=="Unpaid"){
    if(empty($_GET['pro_number'])){
            $shipment = NULL;
        }else{
        $shipment = $_GET['pro_number'];
        }
        
        if($_GET['startDate']){
            $startDate = $_GET['startDate'];
        }
        if($_GET['endDate']){
            $endDate = $_GET['endDate'];
        }
                $start = $_GET['startDate'];
                $end = $_GET['endDate'];
                $status = $_GET['paymentStatus'];
    $date = \Carbon\Carbon::today()->subDays(0);

    $shipments = Shipment::sortable()
    ->where([
        ['due_date','<=',date($date)],
        ['pro_number', 'LIKE', '%' . $shipment . '%'],
    ])
    ->whereRaw('balance > SELECT SUM(p.amount) FROM payments_distributions p WHERE p.shipment_id = pro_number')
    ->whereBetween('date', [$startDate, $endDate])
    ->whereNotIn('shipment_billing_status', [2,3])
    ->paginate(25);
    return view('shipments.accounts', compact('shipments','start','end','status'));
    
}  
}
22 Dec
1 year ago

mprythero started a new conversation Laravel - Importer Mapping Issue

I'm hoping someone might be able to help just look over my code. I'm stuck on an issue and I can't tell if it's just something stupid or if it's just me.

I'm trying to import records using Maat Excel, but it seems to not want to pull a few columns when I try to import.

At the moment, here is my one row test to explain my problem.

    157,2017-06-13,213782,,2017-07-13,5,302,,,,,,0,,,,,0,0,,0,,0,0,54451935,2017-06-13,,,,2017-06-13 00:00:00,,,,,fISHER PRICE,501 MEACHAM BLVD,,FORT WORTH,TX,76106,,,,,,,4,,1,,0,0,0

As you can see, one field in particular "cn_shipfromName" is filled with: fISHER PRICE.

But if you see this error:

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'cn_shipfromName' cannot be null (SQL: insert into `shipments` (`bill_to`, `date`, `pro_number`, `sent_on`, `due_date`, `shipment_billing_status`, `ship_to`, `tractor_id`, `driver_id`, `trailer_id`, `miles`, `fuelChargeDesc`, `fuelChargeAmt`, `fuelChargeTotal`, `permitChargeDesc`, `permitChargeAmt`, `permitChargeTotal`, `otherChargeDesc`, `otherChargeAmt`, `otherChargeTotal`, `Total`, `shipper_no`, `load_date`, `cn_shiptoName`, `cn_shiptoAddress1`, `cn_shiptoAddress2`, `cn_shiptoCity`, `ship_from`, `created_at`, `cn_shiptoState`, `cn_shiptoZip`, `cn_shipfromName`, `cn_shipfromAddress1`, `cn_shipfromAddress2`, `cn_shipfromCity`, `cn_shipfromState`, `cn_shipfromZip`, `cn_billtoName`, `cn_billtoAddress1`, `cn_billtoAddress2`, `cn_billtoCity`, `cn_billtoState`, `cn_billtoZip`, `bill_type`, `print_date`, `shipment_origin`, `void`, `import_balance`, `import_payments`, `freightBillSubtotal`, `created_by`, `updated_at`) values (157, 2017-06-13, 213782, , 2017-07-13, 5, 302, , , , , , , , , , , , , , , 54451935, 2017-06-13, , , , , , 2017-06-13 00:00:00, , , , , , , , , , , , , , , 4, , 1, , 0, 0, , 1, 2017-12-22 06:22:26))

You see fISHER PRICE is left off, as are a few other values.

Right now, this is my controller:

    public function importShipments (Request $request)
    {
        if($request->file('imported-file'))
      {
                $path = $request->file('imported-file')->getRealPath();
                $data = Excel::load($path, function($reader) {
                    })->get();
                    if(!empty($data) && $data->count()){
                        foreach ($data as $key => $value) {
                            $user = Auth::user()->id;
                            Shipment::create([
                              'bill_to' => $value->bill_to,
                              'date' => $value->date,
                              'pro_number' => $value->pro_number,
                              'sent_on' => $value->sent_on,
                              'due_date' => $value->due_date,
                              'shipment_billing_status' => $value->shipment_billing_status,
                              'ship_to' => $value->ship_to,
                              'tractor_id' => $value->tractor_id,
                              'driver_id' => $value->driver_id,
                              'trailer_id' => $value->trailer_id,
                              'miles' => $value->miles,
                              'loadDiscountDesc' => $value->loadDiscountDesc,
                              'loadDiscountAmt' => $value->loadDiscountAmt,
                              'fuelChargeDesc' => $value->fuelChargeDesc,
                              'fuelChargeAmt' => $value->fuelChargeAmt,
                              'fuelChargeTotal' =>$value->fuelChargeTotal,
                              'permitChargeDesc' => $value->permitChargeDesc,
                              'permitChargeAmt' => $value->permitChargeAmt,
                              'permitChargeTotal' => $value->permitChargeTotal,
                              'otherChargeDesc' => $value->otherChargeDesc,
                              'otherChargeAmt' => $value->otherChargeAmt,
                              'otherChargeTotal' => $value->otherChargeTotal,
                              'Total' => $value->Total,
                              'balance' =>$value->balance,
                              'shipper_no' => $value->shipper_no,
                              'load_date' => $value->load_date,
                              'cn_shiptoName' => $value->cn_shiptoName,
                              'cn_shiptoAddress1' => $value->cn_shiptoAddress1,
                              'cn_shiptoAddress2' => $value->cn_shiptoAddress2,
                              'cn_shiptoCity' => $value->cn_shiptoCity,
                              'ship_from' => $value->ship_from,
                              'created_at' =>$value->created_at,
                              'cn_shiptoState' => $value->cn_shiptoState,
                              'cn_shiptoZip' => $value->cn_shiptoZip,
                              'cn_shipfromName' => $value->cn_shipfromName,
                              'cn_shipfromAddress1' => $value->cn_shipfromAddress1,
                              'cn_shipfromAddress2' => $value->cn_shipfromAddress2,
                              'cn_shipfromCity' =>$value->cn_shipfromCity,
                              'cn_shipfromState' =>$value->cn_shipfromState,
                              'cn_shipfromZip' => $value->cn_shipfromZip,
                              'cn_billtoName' => $value->cn_billtoName,
                              'cn_billtoAddress1' => $value->cn_billtoAddress1,
                              'cn_billtoAddress2' => $value->cn_billtoAddress2,
                              'cn_billtoCity' => $value->cn_billtoCity,
                              'cn_billtoState' => $value->cn_billtoState,
                              'cn_billtoZip' => $value->cn_billtoZip,
                              'bill_type' =>$value->bill_type,
                              'print_date' => $value->print_date,
                              'shipment_origin' => $value->shipment_origin,
                              'void' => $value->void,
                              'import_balance' => $value->import_balance,
                              'import_payments' => $value->import_payments,
                              'freightBillSubtotal' => $value->freightBillSubtotal,
                              'created_at' => $value->created_at,
                                'created_by' => $user,
                            ]);
                        }
                    }
                }
        Session::flash('flash_message','Database successfully imported!');
        return back();
    }   

and this is my SHIPMENT model with the parts specific to this issue:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use App\Shipment_Status;
    use App\Shipment_Billing_Status;
    use App\Shipment_Type;
    use OwenIt\Auditing\Contracts\Auditable;
    
    class Shipment extends Model implements Auditable
    {
        use \OwenIt\Auditing\Auditable;
        
        protected $fillable = [
            'pro_number', 
            'shipment_origin',
            'notes',
            'shipment_status',
            'shipment_billing_status',
            'due_date',
            'date',
            'description',
            'driver_id',
            'tractor_id',
            'trailer_id',
            'shipper_no',
            'ship_to',
            'ship_from',
            'bill_to',
            'bill_type',
            'load_date',
            'cn_billtoName',
            'cn_billtoAddress1',
            'cn_billtoAddress2',
            'cn_billtoCity',
            'cn_billtoState',
            'cn_billtoZip',
            'cn_billtoPhone',
            'cn_billtoEmail',
            'cn_shiptoName',
            'cn_shiptoAddress1',
            'cn_shiptoAddress2',
            'cn_shiptoCity',
            'cn_shiptoState',
            'cn_shiptoZip',
            'cn_shiptoPhone',
            'cn_shiptoEmail',
            'cn_shipfromName',
            'cn_shipfromAddress1',
            'cn_shipfromAddress2',
            'cn_shipfromCity',
            'cn_shipfromState',
            'cn_shipfromZip',
            'cn_shipfromPhone',
            'cn_shipfromEmail',
            'fuelChargeDesc',
            'fuelChargeAmt',
            'fuelChargeTotal',
            'permitChargeDesc',
            'permitChargeAmt',
            'permitChargeTotal',
            'otherChargeDesc',
            'otherChargeAmt',
            'otherChargeTotal',
            'noCharge',
            'noSettle',
            'Total',
            'freightBillSubtotal',
            'sent_on',
            'created_at',
            'print_date',
            'void',
            'import_payments',
            'import_balance',
            'miles',
            'sent_on',
            'created_by'
        ];

If you can help, I'd greatly appreciate it. I'm stuck and it's incredibly frustrating not to understand why...

Thanks again -

Matt

19 Dec
1 year ago

mprythero left a reply on Attaching Generated PDF To Mailable (Laravel Snappy)

Well it looks like I finally managed (with all of your help, which I appreciate because I might've gone insane) to get this working with the following code:

    public function __construct(Shipment $shipment)
    {
        $this->shipment = $shipment;
        $this->attachmentURL = $shipment->url_string;
        $shipment_details = $shipment->shipment_details;
        $this->proNumber = $shipment->pro_number;
        $this->path = 'temp/freightbill.pdf';
 
        $this->pdf = PDF::loadView('shipments.pdf', compact('shipment', 'shipment_details'))
            ->save($this->path);
    }

I was curious though, how would you suggest I go about deleting the temp file? I will look into it, but I'm hoping you might have a hint to point me in the right direction.

Thanks again for everything!!

Matt