How to validate Eloquent Models with dynamic patterns and multipe database connections

Loving Laravel and Eloquent Models

Well after some years sticking with Zend Framework, we at me’kono completely fell for Laravel as our main PHP Web development framework, which has a beautiful and easy to read MVC design pattern. One of the most frequently used Classes / Feature of Laravel is the Eloquent Class which – basically speaking – represents an entry in your database and adds methods and relations to it. One very important method is the save()  function obviously, which gathers all the data of the current object instance and tries to save it to the database.

Validation before saving

Since we didn’t want this method to simply run against the database and maybe return an error, the decision was made to have a validation before even starting the storage process. To make things more readable, the validation patterns are stored in a static array in the notation defined by the Laravel Validation Class:

To have these validation rules being applied each time the object gets stored to the database, simply override the save()  method with something like this:

And the isValid()  method we use comes here:

As you can see the method gets all attributes of the object, dynamically creates a Validator from the class’s validation rules and applies them. If validation fails the errors get stored in the object’s errors property. Hence you can better hunt down why storing the data ran into trouble.

Some special DB fields

Ok, this is pretty easy and straight forward, but occasionally you might run into the following problem:
Let’s pick up the common requirement that there should be no duplicate email address in your Users table, i.e. email should be unique. So you can change the validation rule to the following:

If you try this, it works fine if your user’s data is inserted once and then only read from the database, meaning you cannot update it. The eloquent update()  method also uses the save()  method. But since your email is already in the database, the logic just implemented prevents you from storing to the database.

But the guys from Laravel are clever and have taken care of this. You may specify an additional parameter for an ID, which should be ignored or is fine the have the same email (from the docs):

Make it dynamic

Almost there!

Just some additional thoughts: This way all your isValid()  methods have to be custom made for each model. And – you have to distinguish between save operations and update operations. So we came up with the idea of dynamic validation rules. The strings defining the validation are parsed before creation of the Validator and some variables of the object are filled in upon request (changes to above highlighted):

The syntax is dead simple: %[name of object property]$[printf output format]

The array_walk function  iterates over the validation rules and nvsprintf  applies the object properties to the validation strings.

Multiple DB connections and upgrading to Laravel 5.2

When we starting with Laravel, the framework stood at version 4, then we quickly moved to 5.1 – which is the first Long Term Support (LTS) Version of the framework and our project grew bigger and bigger. Now in some parts the framework is using two database connections – even in it model validation. So to search in the correct database for unique values, you have to define, which connection to use. In Laravel 5.1 this may look like this:

We created the Eloquent object over a specific database connection ( User::on('my-other-db')->find($user_public_id); ) and before updating it to the database, the Validator has to be assigned the same database connection.

Now in Laravel 5.2 the validateUnique() method of the Validator Class changed reading the database connection from the defining string. So the database connection has to be set in the validation rules. Since we already had implemented dynamic validation rules this was easy to achieve:

And a slight change to our isValid() method:

 

Aloha Editor: How to create toggling Toolbar Buttons?

As we are preparing our new admin section at me’kono, i was looking for a new up-to-date WYSIWYG Editor to use and finally thought to go with the aloha editor Version 2. To my disappointment the documentation at the time of writing is quite… ah, well… not the best – and simple questions popped up quite fast. So in this first post we’d like to share our findings and how to create toggling formatting buttons for your toolbar in the Aloha editor.

Let’s start where Leap 3 in the very short docs leaves you.

So you got your buttons defined like this:

and your jQuery event handler looks like this:

Now these event handler can set the selection to bold, italic, underline, etc. but don’t reset the style if you click once again. If you have a look at the predefined array of commands, there are no is no help either:

But the unformat object uses a method removeFormatting and after having a look at that, you can figure out how tags are applied on a basic level.

This can be applied to our click handler so we use the Editing.wrap  method too:

Short explanation:

  • aloha.ui.commands  are objects consisting of at least an action property – a function, which gets called. We create this on the fly on lines 5-9.
  • To calculate the tag to wrap around the selection we use the node property of the command in uppercase.
  • To get the clicked command we substract ‚action-‚ from the buttons class property

Well, this should now do the same as before. So what’s the deal here? It’s simple – just change the last parameter of the wrap method call to false and you and up with a toggling formatting button. We do this by checking if the clicked formatting button has the active property – which you should have if you have gotten to Leap 5: Update Button States in the tutorial and simply set an extra active attribute . So our final code looks like this:

So, we hope this helps you create a toolbar for your Aloha Editor with toggling format buttons.

 

Permalink Aside

So you could not resist getting yourself that free upgrade to OS X 10.9 Mavericks and now your local development environment went south? Or you are thinking of upgrading, but first want to know what problems you will have to face? So here is a short list of problems i ran into, what their causes are and how to fix them:

What’s not working (for me)

After upgrading these things were not working anymore:

  • no virtual hosts
  • no php
  • no mysql
  • no mcrypt
  • Zend generating timeouts in various modules

Detecting the first two was quite obvious, but why Zend framework resulted in timeouts was somewhat of a mystery in the first place. Mysql server worked nicely, as i checked that with Sequel Pro – contecting worked fine, all the data was there. So here are the reasons why stuff did not work on my machine:

Reasons for not working

  • no virtual hosts because the upgrade moved my vhost-file to a backup file and did not replicate the already created ones
  • no php because similar happened to the httpd.conf file where by default php module is commented out
  • no mysql (via php) because the default connection sockets are not set in the php.ini, where the previous version also got backup-ed
  • no mcyrpt because it is not completed in the new version coming with OS X 10.9 Mavericks, which is PHP 5.4.17 (at the moment)
  • the Zend timeout occurred because of the missing mysql socket of php

How to fix these problems

So, know that we know the reasons for the errors here are the links and ways to get your development mac up and running again:

  • Go to /private/etc/apache2/extra and check your httpd-vhosts.conf file or another where you have stored your virtual hosts. Usually it simply requires copying the old version indicated by ~orig at the end and renaming it the desired .conf file.
  • Check your httpd.conf (/private/etc/apache2) and enable php5 by uncommenting the line starting with LoadModule php5_module.
  • Reenabling Mysql: there are various websites on the net explaining how to enable mysql on php5 on a mac – so follow that or simply compare your /private/etc/php.ini.default (currently used) with your original from before the upgrade (/private/etc/php.ini-5.2-previous~orig, or similar). Especially watch out for instructions like „mysqli.default_socket = “ where the new version is empty.
  • Ok, installing mcrypt is a longer process. I followed the instructions from Neil Gee and it just worked – many thanks!
  • After your mysql socket is working properly Zend should also be humming again…

Hope this helps everybody who is keen to do the step to Mavericks – it really paid of for me. Just one simple fact to undermine my excitement: 10 GB extra space on my hard drive!!

How to create Waterfall or Pie-Charts and Treemaps in R

Getting things done in R: Waterfall aka Bridge Charts, Multi-level Pie Charts, Bullseye Charts and Sankey diagrams. This is a short round-up of useful pages and resources.

charts and diagrams to impress your audience

If you are hunting for best poster award or want to impress the audience with your presentation at a conference, graphs, charts and diagrams can be a key asset. In contrast to this, my experience from conferences has shown that presenters pay almost no attention how to communicate and visualise their research results. Therefore this post shall introduce you to some amazing but uncommon charts and diagrams and discuss some aspects to consider for creating amazing visual presentations.

me’kono gains further traction throughout october and november 2011

October and November brought me’kono a further boost in visitors and pages views, which increased by 105% (to 1,028) and 99% (to 2,143). During the period of consideration we had 159 conferences listed and 46 deadlines expired. me’kono could help to channel 58 submissions and registrations to these events—an increase of 107%. Our plattform showed 84 People the way to the right conference, up by 155%. So if you want to increase traffic and engagement for your conference, register today!

These are whopping figures and gives us extra motivation to better the me’kono conference plattform further. Hope, you saw our new sharing buttons on top of each conference abstract! Some under-the-hood changes have also been implemented. For instance Google search results will get much better soon, since me’kono pages are pimped with schema.org style microdata. What this means for you, you might ask. Quit simple – your search results will get much more informative and visually appealing. Just check out this one:

In the search results visitors are able to see location, date and description on first glance – much more convenient!

Finally, me’kono has now its own page on Google plus and we are promoting your conferences there as well! For december — besides getting more conferences online — we are preparing some serious website tweaks and some new year’s surprises. So stay tuned, tell us what you think and check back soon!

me’kono is starting to roll – site stats for september/oktober

me’kono started to kick in and is generating interest in the scientific community. To give you a idea how me’kono is performing, here are some statistics for mid-september to mid-oktober (15.09.11 – 15.10.11) period:

We welcomed 502 unique visitors, how read about 1,079 pages in total. The far largest group of visitors are english speaking (59%) – at least according to their browser request language. The most people came from the United States, although here the differences are very small (US: 10.5%, IN: 9.8%, UK: 6.4%).

What could be more important for conference organisors sighting up with me’kono are figures regarding submission and registration: from the 502 unique visitors, 33 went for additional information to the conference pages linked, 13 registered to the conference and 15 submitted either an abstract or a full paper. After considering the bounce rate, this means that about 1/3 of our visitors to a page actually engage in some manner with the enlisted conference.

And yes, I almost forgot it: by 15 October, me’kono had 112 upcoming conferences listed – and we are adding more day by day!

Can amazing jpegmini help shrink large Powerpoint Presentations?

Just recently I came across an amazing new webservice to be found at http://jpegmini.com. You simply upload your jpeg images and can download them after a short time, having them shrinked by up to factor 8. For people running websites with large background images or your personal cloud storage this is amazing! Loadtimes are dropping considerably and you can stuff more images into the same webspace. This service helps you save money and time – and it’s all for free!

Ok, so far this is really useful. But how about shrinking bulky Powerpoint presentations? With some effort and creativity it is absolutely no problem to create a decent presentation of 30 slides weighing in a hefty 5-10 MB. And then your conference host asks you to upload your file onto the university’s server / send it him per email. Will a combination of JPEGmini and Powerpoint help?

To cut it short: No! Powerpoint simply doesn’t care about image sizes and resolution. We tested it with the following setup: took John Picken’s beautiful image from Lake Como from jpegmini website and embedded into a Powerpoint in full size (about 6 MB) and the optimised version (about 1 MB) at a resolution of 3705 x 2829. The result was two files with exactly the same size of about 600KB. After exporting the image out of the ppt, it was clear what happened: Powerpoint simply shrunk the image both times to 974 x 774 (99 KB)!

To conclude, JPEGmini wount help you reducing presentation file sizes. And! Powerpoint is not suitable for large screen presentations – so no HD or similar output!

Permalink | 1 Comment Link

Your research is amazing and your findings are ground-breaking? Then your presentation should emphasise your results by transporting your message in a sufficient and easy-to-follow manner. One way to achieve this, is to use beautiful typography for headlines.

These fonts are usually called ‚display fonts‘ and if you are not stuck in any kind of corporate design enforced by your institute / company, you should definitely check out a recent article at noupe.com featuring some amazing display fonts – and they are all for free: Free Fonts : A Walk on the Grunge Side

Although some might be to rugged, most of them would definitely go well on 1 or 2 slides stating your main message. Just imagine using for instance the font ‚Protest Paint‘ to shout out: „Global Warming is real!“ or „Stop Smoking now!“ and nothing more on one slide. Your audience will definitely remember you as having a clear and valuable statement!

My personal favourite is Wicked Grit, which will be in my next presentation.

What do you thing? Do you have the freedom to use your own presentation layout at conferences?

Kjell

 

one month later: me’kono lists more than 100 academic institutions

August passed by fast, but the crew at me’kono did not waste too much time: we are now listing more than 100 academic entities and research institutions! – and most of them organise a conference. So plenty of choice already here!

The 100th institution happened to be the University of Porto or ‚Universidade do Porto‘. Although not the oldest, it is the largest and best ranking university in Portugal. R&D seems quite fruitful since the university’s members are responsble for 20 % of all Portugiese papers published. By coincidence the Universidade do Porto celebrated 100th birthday this year – so congrats to you guys! Porto is a beautiful city with lots of history, a unique atmosphere and of course the great desert wine is produced there. So, definitely worth a visit.

What else happened in the mean time? After releasing the first version of the plattform me’kono some bugs and misconceptions are removed now and i hope the website got more userfriendly. We especially focused on enhancing the locations section. We hope you like it.

At the moment some internal optimisations are the main focus. And, at the end of September we will introduce some new features for the conference pages. So stay tuned & any feedback very much welcome!

Kjell