Laravel Development with Vessel (Docker)

Getting started with Vessel

I have started using Vessel for my local development as it makes starting and developing a project so much easier. It seems more lightweight than Homestead and the start-up time is much quicker than Homestead.

No PHP or Composer? No problem

If you don’t have PHP7 or Composer installed on your machine, you can follow these instructions to help get you started. It will install PHP7 and Composer environments with Docker and allowing you to create a Laravel project and install Vessel as a package.

I also add /docker folder into my .gitignore as vessel will create this upon initialisation. You could also ignore the vessel and docker-compose.yml files as well, but I enjoy keeping it within my projects.

Bash Commands

Vessel is a bash file and allows you to run any artisan, yarn or npm command of your choosing which makes it easier rather than ssh’ing into a homestead box or running the exec command.

Only for development environments

It has fantastic documentation and should allow you to get running within 10 minutes. The only downside to Vessel is that it’s only for development work and not production. So don’t expect Lets Encrypt certificates or deployment strategies with this.

Want to learn more about going from Development to Deployment? I will be live streaming a learning event Laravel: from development to deployment

If you enjoyed this article, please follow for more. Alternatively, you can Buy me a coffeeBuy me a coffee

 

Laravel 4: How To Use Jquery UI Sortable

Laravel

Click and drag sorting

I needed a way to change the sort order of my data inside of an admin interface which I have created. After a little looking around, I found many tutorials which would show how to get this done with JQuery, but wouldn’t show the best way to handle this data (and in my case using Laravel to handle this data). I dug around for quite a bit, but I ended up finding this lovely little tutorial by dragonfire1119 which was called How To Use Jquery UI Sortable In Laravel 4.

 

The only trouble is, when you follow this tutorial, it could be tidied up a little, here is my version…

// Place this inside your View

@foreach($categories as $category)

sort me

@endforeach

Here is the JQuery…

$(document).ready(function () {
$('.sortable').sortable({
cursor: 'move',
axis: 'y',
update: function (event, ui) {
var order = $(this).sortable('toArray');
$.post('{{ URL::route('Sliders::sort') }}', { order: order });
}
});
});

And then your Controller will look like this…

public function sort()
{
$input = Input::get('order');
$i = 1;

foreach($input as $value) {
$banner = Banner::find($value);

$banner->sort_by = $i;

$banner->save();

$i++;
}
}

The JQuery and Controller could also look like this…

//Jquery
$(document).ready(function () {
$('.sortable').sortable({
cursor: 'move',
action (event, ui) {
var data = $(this).sortable('serialize');

// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
});

Updated Controller…

//Controller
public function sort()
{
$input = Input::get('item');
$i = 0;

foreach($input as $value) {
$banner = Banner::find($value);

$banner->sort_by = $i;

$banner->save();

$i++;
}
}

I think that both work just as well and it is down to personal preference. If you would like to know where I got the second method from, you can take a look here.

As always, if you have any comments/suggestion the please feel free to let me know in the comments.

Laravel Localhost removing /public/index.php

Laravel

I have been in the Laravel chats for quite a while now and one question which I see regularly is how to remove the public/index.php directory on Localhost. The easiest way to do this (and the way I always use) is to open up your Command prompt or Terminal and cd into the main directory of your project then run “php artisan serve”. That’s it. You’re done. Don’t believe me? Check out `https://localhost:8000` and admire your Laravel work.

Another way, but a bit more complicated would be to set up a virtual host (vhost) and point it to the public folder inside your projects main directory. Have a [Google](https://google.com) around if this is what you prefer and you will find so many tutorials showing you just how to do this.

Something which is a lot newer is Vagrant, now this will set up a Virtual Machine which you can SSH into and run a local environment for your PHP. Check it out and find some tutorials on installing a LAMP environment inside your Vagrant project.

Laravel’s version 4.2 will be coming packaged with something called Homestead which will have a Vagrant configuration. This will allow you to go straight into Laravel and run a Vagrant box straight away with little to no configuration what so ever.

So, try each of these examples out and find out which one is easiest for you. If you have another way then please let us know in the comments and share your experiences with setting up a Laravel project.

Laravel Dynamic Navigation Package

Laravel

I have managed to create a dynamic navigation package for Laravel which can be seen in my previous post. If you go to Packagist you will be able to find my package under checkeredmichael/navigation.

I have created a readme with this package which should get you started on implementing it within your own projects. I would like to get as many people as possible to use this package and come back with feedback/bug fixes.

This is my very first public package and I will be using it to expand on other packages such as my very own admin package for Laravel which will be created in the future.

If anyone requires further assistance then please let me know in the comments of this post or contact me.

Laravel Dynamic Menu Tutorial (Best for Admin packages)

Laravel

Learn more Laravel

Want to learn more about going from Development to Deployment? I will be live streaming a learning event Laravel: from development to deployment

 

Creating a dynamic menu

Thanks to this very Laravel topic over at Laravel.io and Josh Benham I managed to find out how to make my very own dynamic menu (which is great if you would like to make a reusable admin package). In this tutorial, I will show you exactly how it’s done and hopefully, you will now be able to make amazing admin packages for Laravel.

For those that just want the package then you can download it the Laravel dynamic navigation package. Otherwise, continue below.

First off, I am doing this in my very own package, so my directory structure will look pretty much like anyone else file structure which will be within the src/Package/Admin. Hopefully, you should be able to follow this along just fine, but if you have any problems or even any suggestions for improvements then feel free to let me know.

Within my Admin folder, I create a new folder called services and create a file called ‘Menu.php’, this is the code you should type within this file…

services/Menu.php

<?php namespace PackageAdminServices;

use Illuminate\Support\Facades\HTML;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\URL; 

class Menu {
    protected $items;
    protected $current;
    protected $currentKey;

    public function __construct() {
        $this->current = Request::url();
    }
    /*
     * Shortcut method for create a menu with a callback.
     * This will allow you to do things like fire an even on creation.
     * 
     * @param callable $callback Callback to use after the menu creation
     * @return object
     */
    public static function create($callback) {
        $menu = new Menu();
        $callback($menu);
        $menu->sortItems();
        return $menu;
    }
    /*
     * Add a menu item to the item stack
     * 
     * @param string $key Dot separated hierarchy
     * @param string $name Text for the anchor
     * @param string $url URL for the anchor
     * @param integer $sort Sorting index for the items
     * @param string $icon URL to use for the icon
     */
    public function add($key, $name, $url, $sort = 0, $icon = null)
    {
        $item = array(
            'key'       => $key,
            'name'      => $name,
            'url'       => $url,
            'sort'      => $sort,
            'icon'      => $icon,
            'children'  => array()
        );
        $children = str_replace('.', '.children.', $key);
        array_set($this->items, $children, $item);
        if($url == $this->current) {
            $this->currentKey = $key;
        }
    }
    /*
     * Recursive function to loop through items and create a menu
     * 
     * @param array $items List of items that need to be rendered
     * @param boolean $level Which level you are currently rendering
     * @return string
     */
    public function render($items = null, $level = 1)
    {
        $items = $items ?: $this->items;
        $attr = array(
            'class' => 1 === $level ? 'menu level-1' : 'level-' . $level
        );
        $menu = '<ul' . HTML::attributes($attr) . '>';
        foreach($items as $item) {
            $classes = array('menu__item');
            $classes[] = $this->getActive($item);
            $has_children = sizeof($item['children']);
            if ($has_children) {
                $classes[] = 'parent';
            }
            $menu .= '<li' . HTML::attributes(array('class' => implode(' ', $classes))) . '>';
            $menu .= $this->createAnchor($item);
            $menu .= ($has_children) ? $this->render($item['children'], ++$level) : '';
            $menu .= '</li>';
        }
        $menu .= '</ul>';
        return $menu;
    }
    /*
     * Method to render an anchor
     * 
     * @param array $item Item that needs to be turned into a link
     * @return string
     */
    private function createAnchor($item)
    {
        $output = '<a class="menu__item" href="' . $item['url'] . '">';
        $output .= $this->createIcon($item);
        $output .= $item['name'];
        $output .= '</a>';
        return $output;
    }
    /*
     * Method to render an icon
     * 
     * @param array $item Item that needs to be turned into a icon
     * @return string
     */
    private function createIcon($item)
    {
        $output = '';
        if($item['icon']) {
            $output .= sprintf(
                '<i class="glyphicon glyphicon-%s"></i>',
                $item['icon']
            );
        }
        return $output;
    }
    /*
     * Method to sort through the menu items and put them in order
     * 
     * @return void
     */
    private function sortItems() {
        usort($this->items, function($a, $b) {
            if($a['sort'] == $b['sort']) {
                return 0;
            }
            return ($a['sort'] < $b['sort'] ? -1 : 1); }); } /* * Method to find the active links * * @param array $item Item that needs to be checked if active * @return string */ private function getActive($item) { $url = trim($item['url'], '/'); if ($this->current === $url)
        {
            return 'active current';
        }
        if(strpos($this->currentKey, $item['key']) === 0) {
            return 'active';
        }
    }
}
<span style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" data-mce-type="bookmark" class="mce_SELRES_start"></span>

Get all that?

This code will set you up for all the behind-the-scenes stuff. Hopefully, most of it is pretty self-explanatory (like most of Laravel) and should be well commented to give you a grasp on what is going on.

Next, we will make our navigation which will be within the views folder, I created an inc folder within my views to keep things tidy called ‘navigation.blade.php’. And my code goes a little like this…

 <?php use PackageAdminServicesMenu; ?>
 {{
     Menu::create(function($menu) {
         Event::fire('admin.menu.build', $menu);
     })->render();
}}

This will display your navigation, but the only trouble is that we haven’t actually built it. Here we have the code to build our dynamic navigation menu. Inside your AdminServiceProvider.php you need to add this line into your public function boot()

include __DIR__.'/../../events.php';

This will tell your package where to find the events page which will build up your navigation (your events.php needs to be in the same place as your routes and filters, which should be in the src folder)…

 <?php Event::listen('admin.menu.build', function($menu){
     $menu->add('index', 'Index', URL::route('Admin::index.index'), 1, 'dashboard');
     $menu->add('users', 'Users', URL::route('Admin::users.index'), 100, 'users');
 });

Here we use the event listen to the method used in Laravel to build our menu, the first part of our add method gives a key which enables a check to see if it’s the current page or not. The second part adds text to your link, URL::route will be the route name which you use in your routes.php. We then have these numbers which says where they should be displayed on the nav and users or dashboard is a font awesome icon.

Phew, that was a lot to take in…

Hopefully, this is enough to get anyone started on a dynamic nav, if you need to use it on more packages then just add the code to the service provider, add another event .php and then create similar code to that above which will build up your navigation even more.

I would also like to thank Josh Benham for his help and support. Check out the discussion at laravel.io.

If you would like to pull in the package I created then take a look at my next post-Laravel dynamic navigation package.

Feel free to add your own feedback in the comments below

Social Networking Website Based in Laravel

Laravel

Laravel social networking website.

I’ve been wanting to make a social networking website for a long time, one which will rival the big guys. I also thought about maybe doing it following the footsteps of Mark Zuckerberg by recording my steps live on my Blog and get feedback to what others think. That way, I can create something which everyone wants and unleash something which almost everyone will love.

I will also release any tutorial worthy stuff as I go through my development to help anyone else who are thinking of making their own social networking sites using Laravel.

I’m starting out with the basics, such as: registration, messaging, pages etc.

What are your likes and dislikes about Facebook, Google+ and Twitter? Let me know in the comments so I can get some awesome feedback.

First Laravel Tutorial – Controllers and Routes

Laravel

Commence quick and helpful tutorial…

Previously on a Laravel project, I had to have a slug within my routes which would point to two different tables within my database. I needed a controller which would do the thinking for me. And by this I mean, in my routes I would have…

Route::get('{slug}', '[email protected]');

And in my Controller, I would have the following to do the thinking for me…

public function index($slug)
{
    if(Page::where('slug', $slug))
    {
        //Show page property
    }
    else if(Blog::where('slug', $slug))
    {
        //Show Blog property
    }
}

So here we have our logic saying if there is anything in the page table where the slug matches. We show the page with that slug otherwise, show a blog post with the matching slug.

This might not be the best example as a lot of people would have a blog post going to ‘blog/{slug}’ and you might even have the page go to ‘page/{slug}’, but the page structure of a site is always changing and it depends on how you feel people should view your site.

I have found one problem with this mind, if nothing gets found then it will just show a blank page, I haven’t found the good logic which will display errors. Or if you are in production a 404 page.