vincej

vincej

Member Since 5 Years Ago

Calgary, Canada

Experience Points 41,710
Experience Level 9

3,290 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 178
Lessons
Completed
Best Reply Awards 2
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 Apr
3 weeks ago

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Sure understood. I guess I am looking for some education as to how Laravel is so clever as to find the correct value from the Category instance, which is returned as an array. I don't want to be asking you a similar question next month :o)

Any ideas?

Many Thanks !!

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

I appreciate that when using Eloquent, category::where() and category::create returns a model instance, but I don't see how Laravel is clever enough to find the VALUE. Also I can now see that when you referred to an object, you did not actually means an object in the real { } sense.

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

@snapey I'm back, Taxes done! OK - first the good news, your suggestion works !!! Hallelujah!

Now for an embarrassing question. When the original error message said that I could not use strings I went to PHPStorm debugger and looked at the contents of $root. Storm said it is an array. So, that freaked me out. Hence my idea that I had to rebuild everything.

Now - more embarrassing questions: with Storm debugger, I look now into the new contents of $root = Category::where('name',$request->parent_category)->first(); and I see that the original of $root is still an array. Not an real object like this { } anywhere. Also there are mountains of values inside $root. So - a bit confused there.

Lastly, Specifically, How in the heck is laravel so cleaver as to work out that of all the possible values inside $root, when used inside $child2->makeChildOf($root); refers to orginal ['name=>VALUE]`. I can send you screen shots of that helps.

I have tried googling object models and the info given does not appear to be relevant to this discussion.

26 Apr
3 weeks ago

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

None of my categories in my views have an id. So, that has to be built, or I guess, I could kludge it, and look up the ID with a query. Perhaps I'm doing things wrong, or over engineering things? Cheers.

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Laracasts us very slow to deliver emails ... like 1 hour! Just saw your last one. Umm .... embarrassing, but I don't understand your other post.

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Many Thanks Snappey !!!

The mistake I made is in not using ID's with Baum. So in order to fix this, I am going to have to rebuild much of the JS which drives my views, as much of the views are constructed out of JS. Major Pain !! I'll get there ... slowly ... Having a good weekend !! I'm sure you will hear from me again next week :o) Cheers !

25 Apr
3 weeks ago

vincej started a new conversation ERROR: Call To A Member Function MakeChildOf() On String

This function comes from a maintained fork of the [Baum package] (https://github.com/gazsp/baum/tree/feature/2.0) for creating nested sets in Laravel 5. @Bashy was happy with it, so, it must be good. I started using the original version and then gave up as it had not been maintained since 2014.

Ok, from the research I have done, I have established that the function, $child2->makeChildOf($node); does not want to see a string. However, I have no idea what else it could be? This is what I have got:

Controller

 public function createBaumCategory(Request $request){

        $category = $request->input('parent_category');  
        $value = $request->input('new_category');
        $v = Category::create(['name' =>$value ]);              // This works ! 
        $this->createCategory->addNode($value,$category);   // Passing into Model
        Flash::success(' Your new category has been created.');
        return redirect('nested_categories');

    }

Model

class Category extends Baum\Node
{
    protected $table = 'categories';
    protected $guarded = ['id'];
    public $timestamps = true;
    protected $primaryKey = 'id';

    
    public function addNode($value, $category)  // Both $value and $category are strings. 
    {   
        $value->makeChildOf($category);         // Fails Here. 
    }

}


Any ideas ?? Many Thanks !!!

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

If I substitute the generic code with real values, I get a different error. So, here is my real controller:

   public function createBaumCategory(Request $request){

        $this->validate($request, [
            'parent_category' => 'required',
            'new_category' => 'required|max:20',
        ]);

        $category = $request->input('parent_category');
        $value = $request->input('new_category');
        $value = Category::create(['name' =>$value ]);
        $this->createCategory->addNode($value,$category);
        Flash::success(' Your new category has been created.');
        return redirect('nested_categories');


    }

My Real Model:

class Category extends Baum\Node
{
    protected $table = 'categories';
    protected $guarded = ['id'];
    public $timestamps = true;
    protected $primaryKey = 'id';

public function addNode($value, $category){

    $value['name']->makeChildOf($category);

}

}

Error Message

Call to a member function makeChildOf() on string

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

When I put it into my model wrapped in the function called createCatgeory() I get an error back:

Call to undefined method App\Models\Category::makeChildOf()

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

I'm stuck with how to make $child2->makeChildOf($root); work inside either my controller or my model.

24 Apr
3 weeks ago

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

I forgot it was Easter weekend and got nothing done.

Embarrassing question time: I have loaded Baum and have been trying things out with Tinker. It has some very useful queries built into it, an indeed you are right, my testing so far shows me that it works with my existing controllers and JS. However, getting the nodes into JsTree is a challenge yet to come :o)

Dumb question: When using Tinker, this works fine:

use App\Models\Category

$child2->makeChildOf($root);

BUT .. when I want to use the same method in my controller it fails even though I have use Baum/Node in my controller. However, the below does work from inside my controller.

$child2 = Category::create(['name' => 'Child 2']);

I guess that works because I am statically calling the create method.

Ok .. so I try another approach. I put the $child2->makeChildOf($root); method into my Category Model as recommended by the user docs, wrapped in a function called createCategory. In the model I also have use Baum/Node ( or else Tinker would not work) and then call that function like so:

$this->categeory->createCategory();

I get an error back.

So - How the heck do I call this kind of method from within the controller. what am I doing wrong here yes, I have initialised $this->category in the constructor.

Any ideas ??? Many thanks as always!!

18 Apr
1 month ago

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Brilliant !!! I will study this later. Gotta go out with the Mrs. I have managed to find a query which will present the top levels, ie Materials, Services. And then I guess, I could just run another query each time the user clicks on a node. In Linux that is how trees work. However I will give this Baum thingee a good look over. I'lll let you know how I get on tomorrow. It's after 12 am for you !!

Cheers !!

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Our posts crossed. Your json is exactly what I need. But I need it from a nested set model. Or I need to be able to reformat the data coming off my table to fit your approach. Sending you my table in case you have a "snapey brainwave" Thanks !!

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Thanks ... you have helped to clarify my thinking. I have found some SQL on Mike Hillyer's website, who is very much the God of this technique. From what I have read "nested sets" are considered the "correct way" of doing things, as the alternative, the "adjacency model", apparently relies upon recursion, which is apparently frowned upon.

The SQL will find the children of a node if you select it. Which means the user is only presented with the top layer of the tree when the page loads, and they would have to select each branch to dig down. Might be ok, not optimum though. I never though something we take for granted in Windows and IOS, is so complicated.

I might need some help in in Laravel to create an array of objects, embedded inside a larger array of objects, embedded inside a larger array of objects. So a kind of multi-dimensional array of objects as depicted above. Sounds terrifying I know.

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

@ snapey - Making progress !! I have as you suggested. I took a step back, and wrote out some simple data into my js, and see what happens. This works, and it gives me the tree as depicted in the image link.

Screen Shot of this

Manually Created Json

   $('#jstree').jstree({
                'core' : {
                    'data' : [
                        { "text" : "Materials", "children" : [

                            { "text" : "Roofing",
                                    "children":[{"text":"Asphalt","children":[{"text":"Achitectural"},{"text":"Laminated"}]},{"text":"Cedar"},{"text":"Rubber"}]

                                },

                                { "text" : "Hardware",
                                    "children":[{"text":"Fasteners","children":[{"text":"Bolts"},{"text":"Screws"},{"text":"Anchors"}]}]
                                }

                            ]
                        },

                        { "text" : "Services", "children" : [{"text":"Sanitation"}]}

                    ]
                }
            });

So - the next challenge I have is how am I going to query a nested set DB table such that it gives me the Json required? I am on the right path thanks to you, however, Any ideas ????

vincej left a reply on How To Format Nested Set Table Data To Work In JsTree?

Hi Snapey!

Thank you for your response. You are the only one to offer some ideas. No one on S.O. has replied either. I will take your ideas to heart.

To clarify: my categories are all encoded using MIke Hillyer's nested set model. I have all queries and views working with them now. There is no turning back now. :o)

I agree that using the "Alternative" flat file method is a problem. So why did I use it? Because I found an old post on SO which suggested I do so, despite having a nested set. Made no sense to me either, but it had a green answered tick next to it, so I have it a go. So, yesterday, I tried the nested set approach using AJAX as described in JsTree and presented above, which is still giving me the same problem. The only postive is that jsTree is trying to load and run, as I get the progress wheel spinning endlessly. :o)

Ok ... all that said, I am now of the opinion that the real source of my problem lies with my query (above). This query produces an array of objects, which I later encode to JSON.

Sample from Query

array (size=20)
  0 => 
    object(stdClass)[525]
      public 'id' => int 1
      public 'text' => string 'Root' (length=4)
      public 'parent' => null
  1 => 
    object(stdClass)[569]
      public 'id' => int 22
      public 'text' => string 'Materials' (length=9)
      public 'parent' => string 'Root' (length=4)
  2 => 
    object(stdClass)[570]
      public 'id' => int 42
      public 'text' => string 'Roofing' (length=7)
      public 'parent' => string 'Materials' (length=9)

Sample Json

[{"id":1,"text":"Root","parent":null},
{"id":22,"text":"Materials","parent":"Root"},
{"id":42,"text":"Roofing","parent":"Materials"},]

As you can see the parent for Root is null as it should be. However, what befuddles me is that JsTree states that when using the "nested" approach with Json, the required data format of the json, no specific fields are required, JsTree takes care of things. Nevertheless, I formated the data to include id and text, as that is suggested by jsTree. Perhaps the parent should be omitted from the data set ? More over, There is nothing I can see in Hillyer's article which explains how to deliver the whole tree without the Root parent being null. Or indeed, I am not sure how to construct a query without the parent being used.

Perhaps I am completely on the wrong track. Don't know ...at the moment I am shooting in the dark.

Does any of this clarify things in anyway? Many ,many thanks as always !!

17 Apr
1 month ago

vincej started a new conversation How To Format Nested Set Table Data To Work In JsTree

I have been trying to use (jsTree.com) to deliver a dynamic tree of categories in my view. However, despite following the instructions as given both their docs as well as those given in Javascripting.com.

Consistently I am getting the JS error: Uncaught TypeError: Cannot read property 'toString' of null I believe this is caused by my nested set table which delivers the root category parent as being null. By definition the Root category can not have a parent. Documentation states that the root must have # as it's parent however gives no clue how to achieve this. Unless of course, I have not properly implemented the JsTree code. I am using the Ajax method to retrieve my table data. JsTree will execute the AJAX.

$(function() {
        $('#jstree').jstree({
            'core' : {
                'data' : {
                    "url" : "/getTree",
                    "dataType" : "json"
                }
            }
        });
    });

Controller

public function getTree(){
         $nodes = $this->category->orderByDepth();
         echo json_encode($nodes);

    }

Model

public function orderByDepth()  // this finds all nodes and their respective depth.
        {  $nodeDepth = DB::select('SELECT category_id AS id,  name AS text, (SELECT name 
           FROM nested_categories t2 
           WHERE t2.lft < t1.lft AND t2.rgt > t1.rgt    
           ORDER BY t2.rgt-t1.rgt ASC
           LIMIT 1) 
           AS parent FROM nested_categories t1 
           ORDER BY (rgt-lft) DESC');
           return $nodeDepth;
        }

21 Mar
2 months ago

vincej left a reply on JQuery: How To Select An Individual Option In A Drop Down Select

I have changed the code entirely since I since I posted that. I was trying to evaluate whether the option was activate or deactivated. Now I remember the use of this, I came up with, which works fine:

 $(".category_select").on("change",".edit_cat", function() {
        var deactivated=$(this).val()==="active"
        if(deactivated == true){
            $(".category_alert").html('<strong>INFO:</strong> Message One ').removeClass("alert-danger").addClass("alert alert-info alert-dismissible")
            }
            else{$(".category_alert").html('<strong>WARNING:</strong> Message Two ').removeClass("alert-info").addClass("alert alert-danger alert-dismissible");

        }

    })

The only problem I now have is working with Jeffrey Way's old v 2.0 flash package. Going to rip all that stuff out of my code and use Laravel flash alerts instead!

vincej left a reply on JQuery: How To Select An Individual Option In A Drop Down Select

Thank you very much!! This set me on the right track, and although the code above is not exactly what I needed it really helped me get it right. I had completely overlooked the use of this.

Three cheers !

vincej left a reply on JQuery: How To Select An Individual Option In A Drop Down Select

Thanks for that. no luck. I have tried every solution on SO. None so far work. Some do not even work on SO!

20 Mar
2 months ago

vincej started a new conversation JQuery: How To Select An Individual Option In A Drop Down Select

I have a table with many rows. Each row, contains a drop drown select with only two 2 options. When the user selects "active" he gets an alert message. If he selects deactivated, he gets a different alert message. The code I have works badly. It only shows one single alert no matter which option is selected. Secondly, the .on(click function()) only fires once per page refresh. I have checked SO a million times, and tried every thing known.

Any advice ? Many thanks !!

From the VIew

<td class="category_select" style="text-align: center">{{ Form::select("category_value[]",['active'=>'Active' ,'deactivated' => 'Deactivated'],$category->status,['class'=>'edit_cat form-control'])}}</td>

JQuery

$("select.edit_cat").on("click",function() {
           if($('select[name="category_value[]"]').find('option:contains("activated")').prop("selected",true))
           {$(".category_alert").html('<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>INFO:</strong> Message One ').addClass("alert alert-info alert-dismissible")}

             else{ $(".category_alert").html('<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a><strong>WARNING:</strong> Message Two ').addClass("alert alert-danger alert-dismissible")}
        });

12 Mar
2 months ago

vincej left a reply on How Best To Translate A Website ?

Good point. I think that I can also go off to some foreign language sites and see how they are labeled and then build a file from there. That works ok, for the European languages ( I speak Dutch, German and French), but it's a huge amount of work though. I had hoped someone just knew of ready made language files which you could download. When it comes to something crazy like Chinese, a person is screwed.

I remember some years ago, when google forst came out with their translation api, and a guy entered "the spirit is willing bu the flesh is weak" into Google translate and it came back: "The whiskey is good but the flesh is rotten". :o)

cheers !

vincej left a reply on How Best To Translate A Website ?

yeah, thanks for that - that actually concerns the issue of how to deal with imported packages and their own language files.

vincej started a new conversation How Best To Translate A Website ?

Ok, I have built all the infrastructure and my application will select and present sample language files inside Laravel resources / lang. I can dynamically alter the language files through a view - it all works.

However, the obvious question now arises - where in the heck do I get the various language files from, or do I really have to google every word I want in every language ? Does anyone know of downloadable language files which are at least accurate and reliable?

Then I chanced across Google's language translation API for PHP, which appears to make the whole Laravel approach redundant.

So - what is the best way to translate a website ? Where can I get language files? Should I use Google instead? What's quickest and easiest since I now have the Laravel infrastructure built?

Many Thanks !

06 Mar
2 months ago

vincej left a reply on How To Sum Two Different Arrays

@CRONIX - Fair comment. About ten years ago I did learn raw PHP through Lynda.com and did some stuff with it in Wordpress and Virtuemart POS system. However, I quickly realised there was a better way with Codeigniter, and so left PHP behind. That is when I first came across you, in Codeigniter. You were a a master there too.

I still reference the PHP manual and the W3schools site regularly to find things not in Laravel, however, yes, I use it only tactically. There is just too much to learn, and time is my single most scarce resource. I spent 26 years working in ERP as a consultant for major international software corps. I have to accept that my application is functionally very rich but not as well crafted as what you or Taylor would deliver.

vincej left a reply on How To Sum Two Different Arrays

Isn't that code in the various if blocks there being executing twice?

Yes, correct. I made that point in my last post. "I assume the others are wrong as well." I will have to change them as well.

This is a brilliant idea! :

public function save_quote_edited(Request $request)
{
    // get the quote type as a variable
    $quoteType = $request->quote_type;
  
    // is there a method in this class that has the same name as $quoteType?
    if (method_exists($this, $quoteType)) {
        // yes! execute it as a dynamic method name and return it
        return $this->$quoteType($request);
    }
}

I was not aware of method exists. I will freely admit that I am not as good as I should be at refactoring my code. Especially all those validations I have that gone on for 100 lines. Jeffrey does not have much in the way of refactoring. In fact, I probably still use Laravel like it was Codeigniter. I love to write code like Taylor Otwell, with really skinny controllers.

You are a rock star, thank you.

05 Mar
2 months ago

vincej left a reply on How To Sum Two Different Arrays

I found the problem. In order to understand the problem, I have to first share with you a small image from my view: (https://drive.google.com/open?id=10VrG79gZODAHTtsP2OeXCkPEuPEwcv4w)

As I was using convertquote it was going to the 3rd option. Where the redirect was wrong. I assume the others are wrong as well. When I changed the redirect to open_quotes, all was well.

**THIS CODE IS USED TO CHECK WHAT THE USER HAS CLICKED **

    public function save_quote_edited(Request $request)  //,$id
    {

        if($request->quote_type =='new_quote') {
            $this->newquote($request);
            return $this->newquote($request);
        }

       if($request->quote_type =='correctquote') {

         $this->correctquote($request);
          return $this->correctquote($request);
        }

        if($request->quote_type == 'convertquote') {
            $this->convertquote($request);
            return $this->convertquote($request);  //THIS SHOULD HAVE BEEN: redirect ('open_quotes');
        }

I am indebted to you. Not only did you solved the addition problem but the looping problem as well.

Thank you is not enough. All the best Vince

vincej left a reply on How To Sum Two Different Arrays

Thanks again - Yes, I fixed the Request $request. F*CK!!, There are two convertQuote hits.. This going to be interesting trying to trace this. But being positive, you helped me ID the likely problem. I'll keep you posted :o)

vincej left a reply on How To Sum Two Different Arrays

back again: so to recap, I have two "loops" being presented with dump() and No, the browser console shows only 1 request being sent.

04 Mar
2 months ago

vincej left a reply on How To Sum Two Different Arrays

Ok, when I do a var dump and disable the redirect, I can see 2 loops reported in the browser, even though I have 3 products on the form.

Not sure what you mean by browser consoles server tab. There is no JS.

I've gotta go - it's 6.23 pm in Calgary and my wife is yapping at me - can we pick this up again tomorrow??

I'm indebted to you. Many, Many thanks !!

vincej left a reply on How To Sum Two Different Arrays

I have discovered something. However, first to answer your questions: The code gets to the server by way of a straight forward form::open() and form::submit()

I made the assumption that the whole controller did not loop multiple times, only that portion of code from $orders[]. I tested that assumption by placing a debug point on the $customer line, and damn it, yes the whole controller is looping. But why ???

public function convertquote($request)
    {
        $customer = $request->only('lastname1'); // debug here. 

vincej left a reply on How To Sum Two Different Arrays

My following comment placed in the code was incorrect:

    // NB: the code never gets to the the foreach below until it has finished looping.  Just to repeat myself for clarity, it will loop the same number of times as there are values in the $orders array. 


vincej left a reply on How To Sum Two Different Arrays

Sorry for the delay, I had to walk the dog :o),

The controller is very long, so a) I have abbreviated it, and b) yes, it needs refactoring. However, here it is:

// THIS TAKES A QUOTATION AND CONVERTS IT TO AN ORDER.  IT ALSO UPDATES THE INVENTORY DB. 

    public function convertquote($request)
    {
        $customer = $request->only('lastname1');
        $ref = $request->input('reference');
        $id = $request->get('product_id');  // GRAB PRODUCT DATA FROM POST ARRAY
        $qty = $request->get('quantity');       // GRAB QUANTITY DATA FROM POST ARRAY
        $line_cost = $request->get('line_cost_hidden');
        $discount_value_raw = $request->get('discountvalue_hidden');
        $discount_value = round($discount_value_raw, 2);
        $count_ids = count($id);


        for ($i = 0; $i < $count_ids; $i++) {
            if (empty($id[$i])) continue;
            $newOrder = new Order();
            $newOrder->reference = $ref;
            // Loads of values go here. 
        // etc etc etc
            $newOrder->save();
        }


        $get_allocation = $this->inventory->allocation($ref);  // This returns an array of "items" each of which is an object containing two values, "inv_product_id" and "allocated".

        $orders = [];
        $orders = array_combine($id,$qty);

        foreach ($get_allocation as $object) {
             if ((!empty($orders[$object->inv_product_id]) )) {
             $orders[$object->inv_product_id] += $object->allocated;
            }
        }


    // NB: the code never gets to the the foreach below until it has finished looping.  Just to repeat myself for clarity, it will loop the same number of times as there are values in the $orders array. 


        //This updates the allocation column in the inventory table with the new order
        foreach($orders as $key=>$value){
            DB::table('inventory')->where('inv_product_id', '=',$key)->update(['allocated' => $value]);
        }


    // This updates the quotations table
     DB::table('quotations')->where('reference', '=',$ref)->update(['status' => 'order']);

        return redirect('open_quotes');

    }

vincej left a reply on How To Sum Two Different Arrays

I know it is looping multiple times because I use phpstorm and I place a whole collection of debug points into the code such that I can follow the order of execution. if I only have a single value in the orders array it executes the first time correctly updates the database and then it returns back to orders and executes the second time.bIf for example I have five values in the orders array it will execute five times.

I'm not sure the empty row in the array is of any real importance as if you hard-code values in the array it loops regardless.

vincej left a reply on How To Sum Two Different Arrays

Good point. My form includes and empty row. I gave you the raw output of the dd($orders), however, in my testing over the weekend, I anticipated that this empty row could be a problem, and so have tried I commenting the $request out, and just hard coded the values into $orders as below, and sure enough it still wants to loop over twice:

 $orders = [123=>"131",789=>"12"];
 //$orders = array_combine($id,$qty);

As for array_filter I tried that as well, and for what ever reason, I could not for the life of me make that work either.

I am now thinking if the foreach can not be made to work, perhaps I could create a DB query which sums $orders and $get_allocation, as both values can be pulled from the DB.

vincej left a reply on How To Sum Two Different Arrays

Thanks for coming back. The orders array is the product of a $request:

 $id = $request->get('product_id');  // GRAB PRODUCT DATA FROM POST ARRAY
 $qty = $request->get('quantity');       // GRAB QUANTITY DATA FROM POST ARRAY

The only the thing that changed from last week was that I had different products and quantities on my form. I have inputed the same products and same quantities and did the dd() as requested:

array:3 [▼
  123 => "131"
  789 => "12"
  "" => null
]

vincej left a reply on How To Sum Two Different Arrays

@cronix I'm having a little problem with that foreach you gave me last week. I have played with this a hundred times which way, I have no idea why it is doing what it is doing. Can you tell me why the foreach is jumping back to the $orders array and looping over it a second time? The result is that it is saving the values into the DB twice. Here is the full set of code so hopefully there is little guess work:

    $orders = [];
        $orders = array_combine($id,$qty);
        
        foreach ($get_allocation as $object) {
             if ((!empty($orders[$object->inv_product_id]) )) {
             $orders[$object->inv_product_id] += $object->allocated;
            }
        }

        //This updates the DB with the new order
        foreach($orders as $key=>$value){
            DB::table('inventory')->where('inv_product_id', '=',$key)->update(['allocated' => $value]);
        }


        return redirect('open_quotes');

The Contents of $Orders looks like this:

$orders = {array} [2]
 123 = "2"
  = null

$get_allocation looks like this:

$get_allocation = {array} [1]
 0 = {stdClass} [2]
  inv_product_id = "123"
  allocated = "2"

Many Thanks !!!! :o)

28 Feb
2 months ago

vincej left a reply on How To Sum Two Different Arrays

@jlrdw Thanks for that. I actually saw that on SO, however, it produced an array of arrays. For me this still created the challenge of of figuring out how to get rid of the key => value, inv_product_id =123 and allocated = 4 when I needed the resulting array to be 123 => 4

Anyway, as you predicted came to the rescue with a beautifully elegant solution. Which I understand now.

If it wasn't for people like you and @cronix and @snapey I would given up years ago. Cheers !

vincej left a reply on How To Sum Two Different Arrays

@cronix Thanks for the explanation. Man I was banging my head against a brick wall with Array_push.

I am very familiar with the += syntax. However, what surprised me is that using this approach, you did not need to create a new array. You did not need to stipulate what would be the keys, nor the values. What also surprised me is that += creates a whole new set of values in the $object array at all. I mean, the preceding values are not overwritten by the last value. I have never used += in this form to achieve this result.

vincej left a reply on How To Sum Two Different Arrays

@harendrasingh Thank you. I do not understand how this works. So I will Google "array of allocations" and that will explain it all ??

27 Feb
2 months ago

vincej left a reply on How To Sum Two Different Arrays

Wow ! That is amazing! Thank you very much. I have to admit that I do not thoroughly understand what is happening here. I have not seen this kind of expression before, where you both sum allocated and inv_product_id, then simultaneously create a new array with just the use of +=

Thank you !

vincej left a reply on How To Sum Two Different Arrays

ok, thanks regular query with subquery it will be.

vincej left a reply on How To Sum Two Different Arrays

I have almost got my query right, but not quite. I need to be able to sum orders and allocated as Total. Any ideas ? Maybe a subquery?? How in the heck do you do one of those on QB ? Many thanks.

 public function customer_order($id) {
        return DB::table('orders')
            ->join('inventory', 'inv_product_id', '=', 'orders.product_id')
            ->select( 'orders.product_id', 'orders.quantity as orders',  DB::raw('SUM(inventory.allocated) as allocated'))
            ->where('orders.reference',   '=', $id)
            ->groupBy('orders.product_id')
            ->get();

vincej left a reply on How To Sum Two Different Arrays

Thanks for that. That makes me smile. How many people in today's world would understand your query. :o)

vincej left a reply on How To Sum Two Different Arrays

Ok, I see it now, "You may also use the count, sum, max, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:"

I guess I use QB because I am old school. :o)

vincej left a reply on How To Sum Two Different Arrays

I don't know either. I have to use QB in order to create the SUM in the query. It doesn't exist in Eloquent. I would post an image from PHPStorm, but I don't know how to post images in mark down.

I am trying a different approach, trying to create a whole new query which will sum the records from the two different tables. No success yet.

vincej left a reply on How To Sum Two Different Arrays

Yes, You suggested that as given above. I tried it and the result is still an array of objects, as given above.

Query:

public function allocation($ref){
       return DB::table('inventory')
            ->join('quotations','product_id','=','inventory.inv_product_id')
            ->select('inv_product_id',DB::raw('SUM(allocated) as allocated' ))
            ->where('quotations.reference','=',$ref)
            ->groupBy('inv_product_id')
            ->get()
            ->toArray();
    }

Controller code:

 $inventory = new Inventory();
  $allocation = $inventory->allocation($ref);

vincej left a reply on How To Sum Two Different Arrays

No, I am not working in JS. The allocation array is returned by a query. The orders array is returned by using the following:

 $id = $request->get('product_id');  // GRAB DATA FROM POST ARRAY
 $qty = $request->get('quantity');

$orders = [];
$orders = array_combine($id,$qty);

vincej left a reply on How To Sum Two Different Arrays

Tried your suggestion and it still produces an array of objects like above. Thanks though.

26 Feb
2 months ago

vincej left a reply on How To Sum Two Different Arrays

Thanks for that. Ok, I will give it a go. I had not thought of that. The collection that comes in from my query is not shown, however it was converted toArray, albeit inside Laravel.