Working with combined expressions in WHERE clauses in Laravel 4

laravel-combined

When retrieving records from tables in our database, you often have to write combined expressions in WHERE clauses like

SELECT * FROM users WHERE status=1 AND (fname = 'John' OR lname='Doe')

The query above is pulling out all users who’s status is set to 1, and fname is equal to ‘John’ or status is 1 and lname is equal to ‘Doe’. Now this query is significantly different from the following one.

SELECT * FROM users WHERE status=1 AND fname = 'John' OR lname='Doe'

Can you tell us what can go wrong with a statement like this? Well to find out more, let’s have a look at how this query will be parsed by database engine

SELECT * FROM users WHERE (status=1 AND fname = 'John') 

OR 

SELECT * FROM users WHERE lname='Doe'

So this query will pull every record that has a status set to 1 and fname equivalent to ‘John’. Then, with the previously pulled records, it will also pull all the users who has a lname equal to ‘Doe’, but this time it will pull out all users disregarding their status. Which means that users with status = 0 or 1 or 2 will also be in the resultset. I bet that is not what you were looking for while you’re writing this query and clearly understands the difference between these two queries. So you got the point of grouping or combining logical expressions and the impact that can have in your resultset. Writing a combined logical expression is easy in SQL. But what if you’re told to do the same operation using Laravel 4’s built in ORM which is called Eloquent ORM. It’s a little tricky to do the same operation in eloquent because of this combined expression, and it needs an anonymous function :) Let’s have a look at the following code in our User model

static function searchByName($fname, $lname){
    return User::where("status", 1)
        ->where(function ($query) use ($fname, $lname) {
            $query->where("fname", '=', $fname)
                ->orwhere("lname", '=', $lname);
        })
        ->get(['*']);
}

Now searchByName(…) function will work as we expected. You can try the following one and see the difference and notice how it is VERY MUCH different from our expectation

static function searchByName($fname, $lname)
{
    return User::where("status", 1)
        ->where("fname", '=', $fname)
        ->orWhere("lname", '=', $lname)
        ->get(['*']);
}

Eloquent ORM’s where function can make use of callbacks in this way. Please note how we used anonymous function as callback that also uses $fname and $lname from the arguments. That’s mainly it. I hope that you’ve enjoyed this article :)

Picking up random elements from DOM using jQuery

tumblr_n1zv0cTukw1tubinno1_1280

Selecting a group of DOM elements is super duper easy these days using CSS selectors, or a particular element via their ID. But what about picking up a random element from these group of elements? In this article I am going to show you how to do it by extending jQuery

Let’s consider that we have the following markup. Now we will pick a random button and change it’s value

<div class="container">
    <button>1</button>
    <button>2</button>
    <button>3</button>
    <button>4</button>
    <button>5</button>
</div>

Let’s extend jQuery and add a random() function to it

$.fn.random = function() {
    return this.eq(Math.floor(Math.random() * this.length));
}

Now we can pick up a random button and change it’s value quite easily.

$(".container button").random().html("Click Me");

That was easy, eh? Hope you’ll like it.

Delegating Events Instead of Direct Binding in DOM

tumblr_n1rr53o21A1tubinno1_1280

When it comes to attaching event listeners, be it a particular element in the DOM, or a group of elements via CSS selectors, most of us bind the event listener directly to the elements. Direct binding is fine when you’re doing for a PARTICULAR element, but it may create problems for a group of elements if you’re not taking extra care while event binding. To understand the issue, let’s have a look at the following code block (Here’s a live example)

 
<!-- index.html -->
<div class="container" style="margin-bottom:50px;"></div>
<input type="button" value="Add More Buttons"  id="addmore" />

And we added the following javascript (depends on jQuery)

 
;(function($){
    $(document).ready(function(){
      $("#addmore").on("click",function(){
        
        var l = $(".container button").length+1;
        $("<button/>").html("Click Me "+l).appendTo($(".container"));
        $(".container button").on("click",function(){
          alert("Clicked");
        });
        
      });
    });
})(jQuery);

Now if you add more and more buttons, you can see that it repeatedly attaching events. See the effect in the following animation

dom-1

To avoid these repeated bindings, you can modify your code like this and detach all the event listeners which were attached previously to these buttons.

$(".container button").off("click");
$(".container button").on("click",function(){
  alert("Clicked");
});

This is boring, lengthy and sometime risky because you have to manually detach events everytime a new DOM element which satisfies your CSS selector rule adds in the container. And if you forgot to do that, chances are higher to break something somewhere.

Now, to save from this pain, jQuery had introduced event delegation which doesn’t bind the event listener to the dom elements but it delegates the event from their parent. This way, you will never have to worry about detaching previous attached event listeners anymore. Let’s have a look at our final code block, and here is a live example too

;(function($){
    $(document).ready(function(){
       
      //event delegation
      $(".container").on("click","button",function(){
          alert("Clicked");
      });
      
      $("#addmore").on("click",function(){
        
        var l = $(".container button").length+1;
        $("<button/>").html("Click Me "+l).appendTo($(".container"));
        
      });
    });
})(jQuery);

In the above example see how we have delegated the click event to every “button” in the container div. Once the delegation is done, it doesn’t matter whenever a new dom element (in this case, a “button”) inserts in the container. It will always capture the “click” event because the parent div “.container” will delegate that event to it properly. All you have to do is select a parent element, and then delegate the event to childrens (via CSS selector) belonging to it. It’s the same .on() method, just takes an extra parameter in the middle which represents the CSS selector to which the event will be delegated.

//event delegation
$(".container").on("click","button",function(){
  alert("Clicked");
});

By using event delegation in jQuery for a group of DOM elements, you can avoid risks, keep your code cleaner and save yourself from some overkill every time. Hope you’ve liked this article :)

How to enable some useful text formatting options in TinyMCE in WordPress

tumblr_na06t4fnlI1tubinno1_1280

Most of the time default TinyMCE editor in WordPress is pretty adequate for everyday text formatting. However, there are a lot of extra formatting options which are hidden out of the box. Enabling these options will give you extra formatting features that will be useful for many of us. In this article, I will show you how to enable these hidden formatting options in TinyMCE. Just add the following code block in your theme’s functions.php file

function tinymce_enable_more_buttons($buttons)
{
    $buttons[1] = 'fontselect';
    $buttons[2] = 'fontsizeselect';
    $buttons[3] = 'styleselect';
    return $buttons;
}

add_filter("mce_buttons_3", "tinymce_enable_more_buttons");

Now you can see these extra options in the editor as shown in the animation below.

format

Hope you liked this article.

Find n number of posts randomly from a group of categories in WordPress

tumblr_n2hutxfrNr1tubinno1_1280

When you are developing a theme, or maybe writing a plugin, it is often required to display related posts in single posts page. These related posts are fetched by various criteria. Sometimes they are fetched from the same categories a post belongs to, or by tags. Sometimes they are set by the author of the posts.

In this article I am going to show you how to fetch the categories of a particular post, and then fetch some random posts from these categories. It’s not as tough as you’re thinking.

Fetch the categories of a post
You can quickly fetch the categories assigned to a particular post using get_the_category() function. Let’s have a look at the following code block

$post_id = 1234;
$categories = array();
$_categories = get_the_category($post_id);
foreach ($_categories as $_cat) {
    $categories[] = $_cat->term_id;
}

Now you have the array of category ids which are assigned to a particular post with post id “1234”.

Fetch posts from these same categories
Now we are going to fetch some posts from these categories fetched in step 1. We will use kinda less documented category__in and post__not_in parameters with get_posts() function. We will make sure that the post “1234” doesn’t come in the list of random posts. Because it will be silly to display that same post as a relative.

$args = array(
        'orderby' => 'rand', //important to fetch random posts
        'post_type' => 'post',
        'numberposts' => 3,
        'post__not_in' => array($post_id), //exclude the same post
        'category__in' => $categories,
        'post_status'=>'publish'
    ); 
$related_posts = get_posts($args);

Now you have an array of 3 related posts, which are related to the post “1234” by belonging in the same categories. Their properties are described in details here in this Codex Article

That was easy, wasn’t it? Hopefully you will find it useful in your next WordPress theme project. Good night.

Passing data from PHP to the enqueued scripts in WordPress

tumblr_nau9zqjZay1tubinno1_1280

Enqueueing scripts, while being as one of the most common tasks for WordPress theme and plugin developers, has a very nice companion feature that can be used to pass data to it. These data will then be available in the native scope of those scripts. In this short article, I am going to show you how to to this

Remember the first parameter of wp_enqueue_script() function? It’s called ‘handle’, and works as a reference point. We need this handle to send some data to it with the help of wp_localize_script() function. Let’s have a look at the following example.

add_action("wp_enqueue_scripts","my_scripts_loader");
 
function my_scripts_loader(){
    $data = array("home"=>site_url());

    wp_enqueue_script("myscript","path/to/my/script.js");
    wp_localize_script( "myscript", "blog", $data );

}

wp_localize_script() takes the handle of the script file, a variable name and an array. Finally, wp_localize_script converts that array into a JSON object and makes available in the local scope of that javascript file via that variable name. So, from the example above you can write the following code in your script.js and it will show you your blog URL, which was actually passed to it using wp_localize_script function

alert(blog.home);

This feature is pretty handy for developing themes and plugins, to pass data from your PHP scripts to the external javascript files. Hope you’ve enjoyed this article.

How to enqueue javascript files properly in the WordPress admin panel

You’d probably have answered the question already, won’t you? We all know that the correct answer is to do that we have to write a function that hooks the “admin_enqueue_scripts” and inside that function we will have to load the script via wp_enqueue_scripts() function. That’s the correct answer, but when it comes to the best practices, it fails. Because when you’re loading a javascript file blindly in all pages, it can be messy and it also may conflict with other scripts which are already loaded in that page. Besides that, why load an extra script everywhere when you actually need it in a specific page, or two perhaps.

The correct, or “precise” way to enqueue a javascript file in the WordPress admin panel is to check first which page you’re on. And when you’re on that specific page where this javascript file is actually required, load it. So how you’re gonna check which page you’re on in the admin panel? The enqueue hook passes a parameter that tells you about this. Let’s have a look at the following example

add_action("admin_enqueue_scripts","admin_scripts_loader");

function admin_scripts_loader(){
    wp_enqueue_script("myscript","path/to/my/script.js");
}

There is nothing wrong with the enqueueing system above. However, the only problem is that it will load your script in every admin page, you need it or not. So let’s write a better version of that admin_scripts_loader function.

function admin_scripts_loader($hook){
    if(in_array($hook,array("post-new.php","post.php","edit.php"))) {
        //specifically load this javascript in post editor pages
        wp_enqueue_script("myscript", "path/to/my/script.js");
    }
}

Now the code is more accurately loading your javascript file only in the post editor pages. This $hook variable gives you the name of the PHP file that you’re on. So it’s quite easy for you to figure out where you should load it.

Hope you enjoyed it.