vincej

Experience

38,600

2 Best Reply Awards

  • Member Since 3 Years Ago
  • 167 Lessons Completed
  • 21 Favorites

26th January, 2018

vincej left a reply on How To Select All Values In An Appended JS Table • 3 weeks ago

Of course I remember you ! You helped me hugely back in those days too ! You should bring back your smeared face pic .. or maybe not :o)

Agreed about Codeigniter. That's where I learned about coding. Laravel is marketed as "easy" ... no where near Codeigniter in terms of ease of use. Nothing beats CI's documentation. Such a shame they hit the wall. It is probably sacrilege to admit, but in many respects I use Laravel in a somewhat Codeigniter manner. View + Controller + model .. dead simple.

Many thanks ! Perhaps a real pic :o)

vincej left a reply on How To Select All Values In An Appended JS Table • 3 weeks ago

thanks ! I was going to delete my query, and you got there before me.

Do you miss Codeigniter ?

vincej started a new conversation How To Select All Values In An Appended JS Table • 3 weeks ago

I need help with how I can grab all the data from a Blade page which contains both appended JS data and PHP data. I have searched over SO and so far can not find a useful solution. Many thanks if you can help !

The problem is that I can not select and upload the values which belong to the dynamically created table. The table is embedded within a Blade page which has ALSO been populated with values using standard Laravel model / controller methods.

I have been trying to serialise with the whole page with JQuery var formData = $("#projectForm").serialize(); and for sure, it grabs the values which are placed within HTML text inputs. However, this approach does not grab the values in my JS appended form even though they too have text inputs .

The embedded table it looks like this:

This table is dynamically created using an ajax call to my model. From there the rows and their respective values are appended into the page like this ( JS function is highly bridged for clarity) :

success: function (data) {
                data.forEach(function (item)    // this takes the array an iterate over it delivering the specific name of the subcategory.
                {
                    product = item.product_name;
                    product_id = item.product_id;
                    quantity = item.quantity;
                    cost = item.line_cost;
                    price = item.price;
                    // table body
                    $("#projectQuotation").append("<tr class='delete_row, .projectTemplate'><td><input type='text' class='form-control  product_done clear_values' readonly value='" + product + "'></td>" +
                        "<td><input type='text' class='form-control  product_iddone  clear_values' readonly value='" + product_id + "'></td>" +
                        "<td><input type='text' class='form-control pricedone  clear_values' readonly value='" + price + "'></td>" +
                        "<td><input type='text' class='form-control  quantity clear_values' value='" + quantity + "'>" +
                        "</td> <td><input type='text' class='form-control  cost clear_values' readonly value='" + cost + "'></td>" +
                        "<input type='hidden' class='form-control line_cost_hidden clear_values' readonly value='" + cost + "'>" +
                        "<td style=\"text-align: center\" ><input type='checkbox'></td>"+    //class='clear_values'
                        "</tr>");
                });

18th January, 2018

vincej left a reply on MySQL: How To RECURSIVELY Sum Values On Different Rows • 1 month ago

@BezhanSalleh Many thanks for your work! I used the slq query in the end. I'm a little embarrassed that I could not work it out for myself. Many thanks! Cheers !

vincej left a reply on MySQL: How To RECURSIVELY Sum Values On Different Rows • 1 month ago

@snapey Heah Snapey, thank you once again for helping out. You always come through. For some reason I could not get get anything out of your query. When I checked in Storm the query came back with zero results. Your select statement is a little different from that of @BezhanSalleh . Anyway, thanks for your work.

vincej left a reply on MySQL: How To RECURSIVELY Sum Values On Different Rows • 1 month ago

Many thanks for your help !

A product can have many orders. So I guess that means it is a 1-m.

Each row in the orders table is defined by an order reference with a product and the quantity.

So Mr. Jones ref # 123 has ordered product abc quantity 12. Also he ordered product XYZ quanity 15. Furthermore he might place multiple different orders.

So maybe Mr. Knowles has done the same.

So as a supplier, I want to know how many of abc I need to have have to full fill both orders. Here is a slightly expanded image of the table which ill illustrate.

link to url

vincej started a new conversation MySQL: How To RECURSIVELY Sum Values On Different Rows • 1 month ago

My orders table has the column "quantity" containing the number of products ordered for that specific product_id. It looks like this:

link to url

So - I have done research and everything I have come up with simply sums the quantity as a whole. This is not what I want. I want MySQL to group the product_id column and then sum the quantity relevant to each specific id. So, for example product id 128 has a sum of 37 and 2334 has a sum of 39.

All the morons on Stack Overflow have told me to sum the whole quantity column.

I have tried with this code and failed miserably:

        return DB::table('orders')
            ->join('products', 'products.product_id', '=', 'orders.product_id')
            ->select('products.product_name', 'orders.id', 'orders.quote_name', 'orders.product_id', 'orders.quantity')
            ->where('orders.status', '=', 'open')
            ->sum('orders.quantity')
            ->groupBy('orders.product_id')   
            ->get();

This gives me an error, or Call to a member function groupBy() on string

I have considered bringing all the values into Laravel and then using Laravel/PHP to filter through and add the order quantities that way, but, there must be a better way using SQL?

Many Thanks !!

15th January, 2018

vincej started a new conversation Why Does My Function Not Finish? • 1 month ago

My function "updateOrder" works in so far that it updates the table correctly. However, for some mysterious reason once it has finished with the for loop the function stops. It does not go onto the Flash::success and the redirect. To test this, I put a dd() just before the flash, and the function never gets there.

I am totally flumixed as to why this is doing what it is doing. advice ? MANY THANKS !

 public function updateOrder(Request $request){

        $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');
        $count_ids = '';

        DB::table('orders')->where('reference', '=',$request->get('reference'))->delete();

        foreach($id as $i){
            if(!empty($i)){
             $count_ids++;
            }
         }

           for ($i = 0; $i < $count_ids; $i++) {
               $newOrder = new Order();
               $newOrder->reference = $request->get('reference');
               $newOrder->quote_name = $request->get('quote_name');
               $newOrder->start_date = $request->get('start_date');
               $newOrder->lead_product = $request->get('lead_product');
               $newOrder->squares = $request->get('square_feet');
               $newOrder->customer_id = $request->get('customer_id');
               $newOrder->product_id = $id[$i];
               $newOrder->quantity = $qty[$i];
               $newOrder->line_cost = $line_cost[$i];
               $newOrder->subtotal = $request->get('subtotal_hidden');
               $newOrder->discount = $request->get('discount');
               $newOrder->discount_value = round($request->get('discountvalue_hidden', 2)); 
               $newOrder->netofdiscount = $request->get('netofdiscount_hidden');
               $newOrder->gst = $request->get('gst_hidden');
               $newOrder->total = round($request->get('final_total_hidden', 2)); 
               $newOrder->comment = $request->get('edit_comment');
               $newOrder->save();
           }

        dd('line 98');                                   // Never gets here ! 
        Flash::success('The Order Has Been Updated');
        return redirect()->route('openOrders');
    }


8th December, 2017

vincej left a reply on Having Trouble With "Unique" Validation Rule • 2 months ago

@snapey, It has taken me a week to get back to this. You are a rock star ! First time a dream ! It works great. I misunderstood the use of the query! Have a good weekend !

vincej left a reply on Having Trouble With "Unique" Validation Rule • 2 months ago

@snapey Thanks for coming back! It's taken me a week to get back to this problem.

Firstly, Yes the session is getting the contractors ID, I checked. Ok, I understand your point. I changed the code to search on the table id and I tried your solution by simply pasting it in.

        $request->validate([

            'contractor_invoice_number'=>'required',
            'contractor_reference' => 'required',
            'workorder_reference'=>'required',
            
       $contractor_id =  session('id'),
           
 'contractor_invoice_number' => Rule::unique('contractor_invoices')->where(function ($query) use($contractor_id) {
             return  $query->where('id',  $contractor_id);
            }),

            ]);

When I run the code I am getting an error:

ErrorException (E_WARNING)
array_map(): Argument #2 should be an array

I am assuming that it is the use($contractor_id) that is screwing things up. But how do I get the $id into the query?

28th November, 2017

vincej left a reply on Having Trouble With "Unique" Validation Rule • 2 months ago

@collabmed nope - what you are proposing will not select the id that is being passed into the rule. What this means is that if say two different contractors have the identical invoice number then it will not be unique to each one specifically. This is the purpose of the new 5.5 unique rule. 5.5 allows you to add a where clause to isolate a specific id.

vincej left a reply on Having Trouble With "Unique" Validation Rule • 2 months ago

Thanks for that, but it didn't work. Same result.

vincej started a new conversation Having Trouble With "Unique" Validation Rule • 2 months ago

Using L5.5.21 and I can not get the "unique" validation rule to work:

use Illuminate\Validation\Rule;

 public function store(Request $request)
    {
        $request->validate([

            'contractor_invoice_number'=>'required',
            'contractor_reference' => 'required',
            'workorder_reference'=>'required',


            'contractor_invoice_number' => Rule::unique('contractor_invoices')->where(function ($query) {
                return $query->where('contractor_invoice_number', session('id'));
            }),

            ]);

            }

When testing, the simple "required" rules work, but the "unique" rule does not. It just skips over the rule and ignores it without any errors.

My objective is to test that the contractor_invoice_number *for that specific "contractor_id" * is unique. Or put another way, the invoice number is not entered in twice.

Perhaps the $query variable is not correct, however the manual does not give instructions on what to put into this variable.

What am I doing wrong?

Many Thanks !

23rd November, 2017

vincej started a new conversation Overriding A Foundation / Auth Trait • 2 months ago

I want to know whether I have done something very bad in overriding a trait by copying it and pasting it into the controller which calls it. It all works fine, however I have seen all kinds of complicated explanations on Laracasts describing how I should be extending classes and stuff .

Details

The trait SendsPasswordResetEmails contains the function:

 public function sendResetLinkEmail(Request $request)
    {
        $this->validateEmail($request);
        $response = $this->broker()->sendResetLink(
            $request->only('email')
        );

        return $response == Password::RESET_LINK_SENT
                    ? $this->sendResetLinkResponse($response)
                    : $this->sendResetLinkFailedResponse($request, $response);
    }

I want to add a few lines of code to it, and so all I have done is copied and pasted the above function with my additional code into the ForgotPasswordController which is calling the trait, and it all works nicely.

15th June, 2017

vincej left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 8 months ago

@lifesound absolutely, 100% use Laravel. Came from raw Php, then codeigniter, now L5.

Just starting learning some Vue in my "free time". So far I love the fact that I no longer have to specify stuff like, $("#myDiv).val() = var x but it for me still early days.

14th June, 2017

vincej left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 8 months ago

@lifesound I use JavaScript and jQuery extensively any new technology must pay for itself in terms of increase productivity and Superior manageability

13th June, 2017

vincej left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 8 months ago

@lifesound what's your point ?

vincej left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 8 months ago

I'm an independent dev. The single most expensive resource I have is time. For me, training and learning is the single most expensive thing I can do. The more "cool" tech the more expensive it gets. I MUST focus on the "Why should I use this". I must focus on delivering a business solution to my customers. If new tech does not drive productivity quickly, I don't I won't eat.

vincej left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 8 months ago

@MikeHopley I'm old school. I still prefer to use raw SQL when it fits. Your comment resonates with me. I find that in today's world there is a huge draw towards ever newer and "cooler" technologies. The net result is that you can grossly over engineer an application.

12th June, 2017

vincej left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 8 months ago

@jaydeluca I use a lot of JQuery AJAX. My understanding is that Vue does not have an alternative for that. What do you do when / if you need ajax?

9th June, 2017

vincej left a reply on How To Add A Bootstrap Glyph-Icon To A Collective Link_to() • 8 months ago

Outstanding ! it worked. I should have known better to remove the link_to() and replace it with an a href

  <li class="active"><a href="quotes"><span style="color:#11569E" class='glyphicon glyphicon-cog'></span>  Manual Quote</a> </li>

thanks !

vincej started a new conversation How To Add A Bootstrap Glyph-Icon To A Collective Link_to() • 8 months ago

Bootstrap requires that you wrap your icons in a span like this:

<span class="glyphicon glyphicon-search" aria-hidden="true"></span>

Great, been using that elsewhere in my project with success, however, when it comes to a link_to() things fall apart.

I want the icon to appear right next to the text. I have tried a multitude of different approaches and whilst the icon does appear, I can not get it next to the text. If I do get it next to the quote, the icon does not render. I get the html code instead.

I only want icons against the top level of the nav bar and not on the drop downs for example, "Manual Quote" , "open quotes" and "Closed quotes".

 <ul class="nav nav-tabs">
        <li class="active">{!! link_to('quotes', 'Manual Quote' ) !!}  </li>
            <li class="dropdown">
                <a data-toggle="dropdown">Project Quote<span class="caret"></span></a>
                <ul class="dropdown-menu">
                    <li>{!! link_to('project_quote', 'Create Project Based Quote' ) !!}</li>
                    <li>{!! link_to('project_template', 'Create Project Template' )!!}</li>
                    <li>{!! link_to('project_edit', 'Edit Project Template' )!!}</li>
                </ul>
            </li>

        <li>{!! link_to('open_quotes', 'Open Quotes') !!}</li>
        <li>{!! link_to('quotes_history', ' Closed Quotes History' ) !!}</li>
    </ul>


What am I doing wrong ? Many thanks !

8th June, 2017

vincej left a reply on ->groupBy() Results In Error • 8 months ago

@jlrdw

THANK YOU !!! I upgrade to Mysql 5.7 and all my Group By's didn't work. I tried ALL the solutions given on SO and nothing appeared to work. I've spent hours on this. Never thought of app / config.

btw - thanks for the bookmark !

5th June, 2017

vincej left a reply on How To Find The Differences Between Two Arrays When They Are In Different Formats? • 8 months ago

Got 'er done. I hope this might help someone else.

Instead of trying to array_diff() the $nodes and the $result array, both of which are derived from the same sql query, I introduced a second query creating the array $categories. Although this array was a collection, it was not multi dimensional. So, I could convert it to a plain array with toArray(). From there I could use array_diff($categories, $result) and got what I needed.

cheers.

vincej left a reply on How To Find The Differences Between Two Arrays When They Are In Different Formats? • 8 months ago

good comment. For me "different" means different values. $result is a subset of $nodes. I which to create a new array where the values from $result are no longer included. I hope that makes sense. My challenge is I don't know how to get them into the same shape.

vincej started a new conversation How To Find The Differences Between Two Arrays When They Are In Different Formats? • 8 months ago

I have two arrays, $nodes and $result. I want to create a third array, showing the differences. This might have been easy using something like array_diff() however, my two arrays are in a different format and here is where I am getting into trouble:

$nodes array is the result of a raw SQL query and looks like this ( abbreviated):

array (size=12)
  0 => 
    object(stdClass)[434]
      public 'name' => string 'Architectural' (length=13)
      public 'depth' => int 4
  1 => 
    object(stdClass)[435]
      public 'name' => string 'Asphalt' (length=7)
      public 'depth' => int 3
  2 => 
    object(stdClass)[436]
      public 'name' => string 'Cedar' (length=5)
      public 'depth' => int 3

$resultarray is the outcome of filtering the $nodes array with a for loop to find those nodes with a certain depth. It looks like this:

array (size=3)
  0 => string 'Materials' (length=9)
  1 => string 'Root' (length=4)
  2 => string 'Services' (length=8)

I want to compare the two arrays, and find those values which do not appear in the $result array.

I have tried to get them into the same format with $nodes->toArray() but that doesn't work.

Any ideas how I might how I can find the differences in two arrays?

Many thanks !

30th May, 2017

vincej left a reply on Ide-helper Install Breaks Artisan • 8 months ago

I deleted and repasted the class reference from packagist. then I restarted Storm, and it all seems happy now.

Never happened to me before with a composed install.

Thanks !

vincej started a new conversation Ide-helper Install Breaks Artisan • 8 months ago

I just installed Barry's IDE-helper v2.3.2, using composer.

Following the instructions on packagist. I added Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,` to my providers array in config/ app.

The first thing I notice is that I am not getting auto complete in PHPStorm. So, I run php artisan ide-helper:generate as suggested by many posters. I get an error:

  [Symfony\Component\Debug\Exception\FatalThrowableError]  
  Parse error: syntax error, unexpected '}'     

So I attempt to run other artisan commands like clear-compiled as also suggested by other posters. Again the same error.

Even just running php artisan now gives the same error.

Any recommendations ? Just remove the thing?

18th May, 2017

vincej left a reply on Custom Validation Attributes Does Nothing... • 9 months ago

@bobbybouwmann

Hi ! I need some advice with how to change the attributes on a dynamic array with the only identifier is an ID number I am validating an array like this ( this works):

  $messages = [
            'required' => 'The :attribute field is required!',
        ];


        $validator = Validator::make($request->all(),
            [
                'cat_name.*'=>'required|max:20',
                'notes.*'=> 'required|max:200'
            ],

        $messages

        );


        if ($validator->fails()) {
            return redirect('edit_categories')
                ->withErrors($validator)
                ->withInput();
        }

But the error messages look terrible. As you can see it uses the field name:

    The cat_name.25 field is required!
    The notes.1 field is required!
    The notes.25 field is required!

There are many rows to the form, so it would be useful to be able to advise, "Category Name with ID 25 is Required"

Can it be done ?

Heel veel bedankt !

Many Thanks !!

vincej left a reply on How To Get Required $_POST Into Required Shape For Array Validation ? • 9 months ago

@jlrdw I like the approach !

But what is this: Cln::fixValue I have not seen this before.

vincej left a reply on How To Get Required $_POST Into Required Shape For Array Validation ? • 9 months ago

@snapey @bunnypro @jldrw

I go it ! Blade does not like the double braces {{}}. Also I changed it to a foreach loop. You have to put quotes and concatenate inside the the [id] name of the input field. The docs are

This works, and validation is now also working !!! I now need to customise the messages - joy :) Anyone who says Laravel is easy to use is talking out their butt. CodeIgniter is easy, but relatively lightweight compared to Laravel.

Many thanks !

 <tbody>
        @foreach($categories as $category)
        <tr>

 <td>{!! Form::text('cat_name['.$category->category_id.']',$category->name)!!}</td>
            <td>{!! Form::textarea('notes['.$category->category_id.']',$category->notes])!!}</td>
            <td>{!! Form::select('status[]', ['active'=>'Active' ,'deactivate' => 'Deactivate', 'delete' => 'Delete'],$category->status , ['class'=>'edit_cat form-control'])!!}</td>
    
 </tr>
        @endforeach
        </tbody>

vincej left a reply on How To Get Required $_POST Into Required Shape For Array Validation ? • 9 months ago

Thanks guys, I have tried putting the {{$i}} counter inside the blade syntax but, Blade will not render the statement.

Furthermore, as my controller is submitting to the view a collection which I loop over, I have to include $categories[$i]->namewithin the Blade statement like this:

<td>{!! Form::text('cat_name[]', $categories[$i]->name,)!!}</td>

vincej started a new conversation How To Get Required $_POST Into Required Shape For Array Validation ? • 9 months ago

The docs stipulate that in order to validate an array, the POST must to fit into this shape: https://laravel.com/docs/5.4/validation#validating-arrays

$validator = Validator::make($request->all(), [
    'person.*.email' => 'email|unique:users',
    'person.*.first_name' => 'required_with:person.*.last_name',
]);

or as Matt Stauffer explains: https://mattstauffer.co/blog/form-array-validation-in-laravel-5-2

array(2) {
  ["name"]=>
  string(10) "Acme, Inc."
  ["employee"]=>
  array(2) {
    [1]=>
    array(2) {
      ["name"]=>
      string(10) "Joe Schmoe"
      ["title"]=>
      string(11) "Head Person"
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(18) "Conchita Albatross"
      ["title"]=>
      string(21) "Executive Head Person"
    }
  }
}

Question:

So, when I submit my view with all the form entries, I can not see how to structure data so that it will fit this required shape. I have tried both foreach and a for loop. This is what I have got. HOw do I reshape my form so that when it is submitted it fits the required shape for validation?

 <tbody>
        @for($i=0; $i<$count; $i++)
        <tr>
            <td>{!! Form::text('cat_name[]', $categories[$i]->name,  ['class'=>'edit_cat form-control'])!!}</td>
            <td style="text-align: center">{!! Form::textarea('notes[]',$categories[$i]->notes,['class'=>'form-control','id'=>'notes','rows'=>'1'])!!}</td>
            <td style="text-align: center">{!! Form::select('status[]', /*$categories[$i]->status,*/['active'=>'Active' ,'deactivate' => 'Deactivate', 'delete' => 'Delete'],$categories[$i]->status , ['class'=>'edit_cat form-control'])!!}</td>
        </tr>
        @endfor
 </tbody>

It produces an array like this:

array:5 [▼
  "_token" => "C2xi6sLilJVQecfQ4UfrMf4ngGwTY1rEOOSe8Qki"
  "cat_id" => array:4 [▼
    0 => "26"
    1 => "24"
    2 => "1"
    3 => "25"
  ]
  "cat_name" => array:4 [▼
    0 => "cedar"
    1 => "Materials"
    2 => "Products"
    3 => "slate"
  ]
  "notes" => array:4 [▶]
  "status" => array:4 [▶]
]

17th May, 2017

vincej left a reply on How To Validate Array From View - I Keep Getting An Error Message. • 9 months ago

No matter what I do I end up with a POST array that looks like this:

array:5 [▼
  "_token" => "93sfV3Lvtx2weQa5XgxJGyIVkV5Nv9qbAcuDtcSM"
  "cat_id" => array:4 [▼
    0 => "26"
    1 => "24"
    2 => "1"
    3 => "25"
  ]
  "cat_name" => array:4 [▼
    0 => "cedar"
    1 => "Materials"
    2 => "Products"
    3 => "slate"
  ]
  "notes" => array:4 [▶]
  "status" => array:4 [▶]
]


vincej left a reply on How To Validate Array From View - I Keep Getting An Error Message. • 9 months ago

too right ! :)

thanks for the code.

I am going to try running the POST data through a foreach and validating one by one like you suggest.

vincej left a reply on How To Validate Array From View - I Keep Getting An Error Message. • 9 months ago

Good idea, I will think on that. I could also take the easy way out and use the either js validation or even HTML5 validation.

vincej left a reply on How To Validate Array From View - I Keep Getting An Error Message. • 9 months ago

@jldrw Thank you very much for your suggestion.

I have spent the day studying Matt's format very carefully, and trying all kinds of things out built on his code. Sadly, all to no avail. The irony is that the L5.4 docs actually make the comment:

"Validating array based form input fields doesn't have to be a pain"

Well, I hate to say it, but it is nothing but a major pain.

The problem lies in the fact that in order to make array validation work, the $_POST has to be in a very specify format. Any deviation and validation fails. It should be easy, but, nope, I've tried using Blade and raw PHP and it beats me.

Matt's example, assumes that you are building a straightforward input form with multiple rows:

<input type="text" name="employee[2][name]">

Getting this into a format which Blade can handle using a for loop, as I have multiple dynamic values, and which in turn spits out the correct shape of the $_POST array is anything but easy. I have also tried using raw PHP, and can't get the POST array right.

It has to look like this:

array(2) {
  ["name"]=>
  string(10) "Acme, Inc."
  ["employee"]=>
  array(2) {
    [1]=>
    array(2) {
      ["name"]=>
      string(10) "Joe Schmoe"
      ["title"]=>
      string(11) "Head Person"
    }
    [2]=>
    array(2) {
      ["name"]=>
      string(18) "Conchita Albatross"
      ["title"]=>
      string(21) "Executive Head Person"
    }
  }
}

cheers !

vincej started a new conversation How To Validate Array From View - I Keep Getting An Error Message. • 9 months ago

Using 5.4

My view is made up of many dynamically created rows all containing data with the same name:

  <tbody>
 @foreach($categories as $category)
        <tr>
             {!!Form::hidden('cat_id[]', $category->category_id)!!}
            <td>{!! Form::text('cat_name[]',$category->name,['class'=>'edit_cat form-control'])!!}</td>
            <td style="text-align: center">{!! Form::textarea('notes[]',$category->notes,['class'=>'form-control','id'=>'notes','rows'=>'1'])!!}</td>
            <td style="text-align: center">{!! Form::select('status[]', ['active'=>'Active' ,'deactivate' => 'Deactivate', 'delete' => 'Delete'],$category->status , ['class'=>'edit_cat form-control'])!!}</td>
        </tr>
        @endforeach
  </tbody>

It all works great, until I try to validate the data:

  $validator = Validator::make($request->all(),
            [
                'cat_name.*'=>'required|max:20',
                'notes.*'=> 'max:200'
            ]
        );

        if ($validator->fails()) {
            return redirect('edit_categories')
                ->withErrors($validator)
                ->withInput();
        }

If I intentionally create an error, I get an error message:

ErrorException in helpers.php line 533: htmlspecialchars() expects parameter 1 to be string, array given

I have removed all of the escaping from my form, so I have no idea why htmlspecialchars is being invoked. Posts on SO suggest that the select is to blame .. but if I comment it out, it makes no difference. If I comment out validation, then my updates work.

If I do a dd($errors) I am getting the errors through.

ViewErrorBag {#392 ▼
  #bags: array:1 [▼
    "default" => MessageBag {#393 ▼
      #messages: array:1 [▼
        "cat_name.0" => array:1 [▼
          0 => "The cat_name.0 field is required."
        ]
      ]
      #format: ":message"
    }
  ]
}

What am I doing wrong ??

Many thanks !!

12th May, 2017

vincej left a reply on How Best To Save Multiple Rows Of Table Data Into The DB • 9 months ago

hmm .. I could try putting the $category_id into the ` like this:

<td id =$category_id> <td>

Then in the controller, group by category_id before saving.

I'll give it a try. Thanks

vincej left a reply on How Best To Save Multiple Rows Of Table Data Into The DB • 9 months ago

@MaverickChan using 5.4

A more traditional way ?? Can you please give me a hint what you mean. Perhaps not using a table, but rather a series of text inputs ?

vincej started a new conversation How Best To Save Multiple Rows Of Table Data Into The DB • 9 months ago

Essential Question: How to upload my table data so it can be correctly saved?

Within my view, I have a table with 3 columns and multiple rows. The rows are populated correctly with a foreach:

 <tbody>
        @foreach($categories as $category)
        <tr>
            {!! Form::hidden($category->category_id)!!}
            <td>{{Form::text('cat_name[]',$category->name,['class'=>'edit_cat form-control'])}}</td>
            <td style="text-align: center">{{ Form::textarea('description[]',$category->notes,['class'=>'form-control','id'=>'notes','rows'=>'1'])}}</td>
            <td style="text-align: center">{!!Form::select('amend[]', ['active'=>'Active' ,'deactivate' => 'Deactivate', 'delete' => 'Delete'], 'Active', ['class'=>'edit_cat form-control'])!!}</td>
          
        </tr>
        @endforeach
        </tbody>

The user can change the spelling of a category name, or add a comment, or deactivate the category through a select drop down.

Great - so now I want to upload the form with all the changes and save the data to my DB. Somewhere I remember that you need to convert each named field into an array, hence why I applied [] to all the field names. However, note, it makes zero difference to the success / failure of my task.

When the data comes into the controller using this: $input = $request->all(); I am not getting a well organised series of arrays. My data:

array:13 [▼
  "_token" => "DKwMRNVqSvrOraEXdARba05b99WSWlaFqcMOxMVI"
  15 => null                             // This is a category id number 
  "cat_name" => array:9 [▼
    0 => "Architectural"
    1 => "Asphalt"
    2 => "Ceder"
    3 => "Hardware"
    4 => "Laminated"
    5 => "Materials"
    6 => "Nails"
    7 => "Roofing"
    8 => "Rubber"
  ]
  "description" => array:9 [▼
    0 => "Here is a nice comment"
    1 => "Another nice comment"
    2 => null
    3 => null
    4 => null
    5 => null
    6 => null
    7 => null
    8 => null
  ]
  "amend" => array:9 [▼
    0 => "active"
    1 => "active"
    2 => "active"
    3 => "active"
    4 => "active"
    5 => "active"
    6 => "active"
    7 => "active"
    8 => "active"
  ]
  13 => null
  22 => null
  14 => null
  16 => null
  10 => null
  17 => null
  12 => null
  20 => null
]

As always - Many Thanks !!

5th May, 2017

vincej left a reply on How To Change CSRF Token And /or Session Data After Password Change ? • 9 months ago

Yes ! That worked. thanks !

btw - did you know I am a dual national? Lived in Herts for 26 years. British wife, kids and British Education.

vincej left a reply on How To Change CSRF Token And /or Session Data After Password Change ? • 9 months ago

@snapey

Success ! Many Many Thanks !!

I had to make a couple of mods to your code:

$request->user->password came back with:

Trying to get property of non-object

I checked with Storm debugger and found nothing, So I changed that bit back.

Then on the very last statement, it was puking with a redirect, so I changed that to a return and it worked: return view('contractor_portal/change_password',compact('name'));

Changing Subjects I notice that good developers like you write much more abbreviated code. I really want to be able to do the same, but I am having a real problem finding all these little cool functions like back() or fill() or what ever. I am reading the source code more and more, and I see these little funky functions all over the place. But I find looking them up in the API is major pain. I can spend 10 mins before I find it. The search function in the API is not the easiest. And then it is still not clear what they do. Perhaps I was spoilt during my CodeIgniter years when everything was searchable in seconds. I bought Matt Stauffers book who also admits that he learned loads of new things about Laravel during it's writing. If Matt learns new stuff, people like me are really going to have to work hard.

Question How did you find out about all this stuff ?? Does a person really have to digest the source code? I don't know if I have the stomach for that. Any tips / advice ? How did you do it ?

Thanks !

vincej left a reply on How To Change CSRF Token And /or Session Data After Password Change ? • 9 months ago

@snapey Thanks for your rapid reply !

This is how my controller works so far. I am not doing anything with the guard or csrf:


    public function password_update(Request $request){

        $this->validate($request,
            [
                'old_password'  => 'required',
                'new_password'  => 'required',
                'new_password2' => 'required|same:new_password',
            ]);

        $user = User::find(Auth::id());

        $old_password1 = $user->password; // From DB

        if(password_verify($request->old_password,$old_password1)) {
            $new_password = hash::make($request->new_password);
            $user->password = $new_password;
            $user->save();
            flash::success('Password has been updated');
            return view('contractor_portal/change_password');
        }
        else {flash::error('The Old Password is Not Valid');}


    }


vincej started a new conversation How To Change CSRF Token And /or Session Data After Password Change ? • 9 months ago

I have built a feature where a user can change their password after having logged in. (I am aware of reset pw feature, however that assumes you are not yet logged in yet.)

Ok - so I have my change password view working great. Also my change pw controller is working great. My controller checks the old password from the DB against the submitted pw in the form and then proceeds to hash and save a new pw. All Good !

Problem: Once the password has been changed, if I now go to another page on the site, Laravel kicks me out to the login page. I am guessing that this is because there is a now mismatch either with the CSRF token or perhaps more likely, the default web guard session data as created within the config/Auth. I don't know either way.

Any ideas nad help as to what I need to do to ensure that once a pw change has occured that the user will not get kicked out ?

Many thanks !

29th April, 2017

vincej left a reply on Can't Make Auth::guard Work As Expected. • 9 months ago

@jimmck Once again, many thanks for al your help and feedback!

However, you have got me very wrong, I am actually very chill and not frustrated at all. Just always eager to overcome obstacles and always learn more. I am most certainly not a beginner. Perhaps that might give that impression, but that might be because a raging detail person.

My application as it stands today is many, many thousands of lines of Laravel, Javascript and Jquery code. Out of the box Authentication as given in the user docs is a walk in the park. That is not the challenge I am trying to overcome. I am wanting to deliver multi-authentication with multiple user types, and very specific user login and logout pages. Everything I have read and watched states that Laravel has major, major weaknesses in this area. Indeed some commentators state it can not be done with Laravel's current authentication structure, such is the gravity of the challenge. This is not only my opinion but the opinion of many commentators, and looking at the dialogue over the last 2 pages, it appears that reality is borne out. However, I have an idea on how to overcome the challenge. I'm optimistic.

Lastly, in my effort to accelerate my learning of Laravel, I have been searching through the API docs as you recommend. As already stated, I find these too not very accessible.

As always, many thanks for all your help, time and support!!

28th April, 2017

vincej left a reply on Can't Make Auth::guard Work As Expected. • 9 months ago

@jimmck yup, for the last few w3ks I have been studying the API together with the source. I just wish it was easier to find what you are looking for in the API. I can waste 10-15 mins trying to find a single method. Any tips on how to find stuff quickly?

vincej left a reply on Can't Make Auth::guard Work As Expected. • 9 months ago

@snapey @jfadich

Guys, my wife has just called me, and demands I come home as it's Fri. Heaven knows how late it is in the UK, 11.20pm! so I will have to suspend this conversation till monday. I hope you guys will bear with me, as truly, multi- authetication is a major pain in Laravel no one so far has managed to help me fix this. I have even tweeted Taylor about it. I'm hoping he will blog about it next week. It appears that most people just use 2 login screens and 2 logout screens which for me is really messy.

As always Many Thanks, have a good one !!!

vincej left a reply on Can't Make Auth::guard Work As Expected. • 9 months ago

@snapey ok, can I extract the name from this ?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.