Populate dropdown list from database with Laravel

While building admin/CMS or just a form on your site you might need to build a dropdown (select) list with values read from database. It is very elegant to do this with Laravel’s Eloquent. (For the sake of this post let’s assume that you want to read values from the database and not from some array stored in a class or somewhere else.)

Let’s suppose the database table is called “countries” and is already populated (You can get one here). It contains, you guessed it, a list of country names, which you would like to display in a HTML dropbox list.

First, create a model named “Country.php” (you can use artisan, excellent  Laravel 4 generators or create it manually. Keep in mind that the model name is singular (Country) and the database table is plural (Countries).

In your controller add:

$country_options = Country::lists('short_name', 'id');

Simple isn’t it? This will return an array of values like “[1] => Afghanistan [2] => Aland Islands”… (We are assuming that database field name containing country names is “short_name”).

Note: Personally I like Eloquent but in case you do not want to use Eloquent or/and do not want to have an empty Country.php model lying there just so you can populate drop-down then you can use Laravel’s Fluent Database Query Builder:

$country_options = DB::table('countries')->orderBy('short_name', 'asc')->lists('short_name','id'); 

Ok, now let’s send this to view with ->with :

return View::make('admin/customers/create')->with('country_options',$country_options);

In above case I am sending $country_options to admin view that is used to create customers.

In the view you display it like this:

 {{ Form::select('country', $country_options , Input::old('country')) }}

That is all it takes to have a functioning drop-down select box. As you can see we are using Laravel Blade template engine and Form class. With Input::old('country')) we re-populate it with old values (for example after the form is submitted and there are some errors)

How to combine more fields with concat

In another case (for “customers”) I needed to combine two table fields into one and then populate the drop down with it: customers “first_name” + “last_name” should be “first_name last_name”. You can do this by combining Fluent Query Builder with Eloquent:

$customer_options = Customer::select(DB::raw('concat (first_name," ",last_name) as full_name,id'))->lists('full_name', 'id');

As you can see we are mixing Eloquent and DB:raw method.

Note: If you only want to use Laravel’s Database Query Builder then you can do this:

$customer_options = DB::table('customers')->select(DB::raw('concat (first_name," ",last_name) as full_name,id'))->lists('full_name', 'id');

How to add default option to dropdown list

Sometimes we want to have some default value that gives us some instructions what to do (“Please select a country,…”) with the dropdown or maybe even some default “non-value” (in case user doesn’t want to select anything). The easiest way to do this is to add array('' => 'Select One') + so our code looks like this (few examples with the code in this post):

$country_options = array('' => 'Please Select Your Country') + Country::lists('short_name', 'id');
//or
$customer_options = array('' => 'Select Customer') + Customer::select(DB::raw('concat (first_name," ",last_name) as full_name,id'))->lists('full_name', 'id');
//and so on..

Keep in mind that you will have to add some validation (jQuery, Laravel’s own validation etc) in case user leaves the default option (in example above we leave the value as empty but you can set it to anything you want).

I really love Laravel 4, it makes developing so much fun and simple.

Laravel erorr: Call to undefined method Illuminate\Foundation\Application::getConfigLoader()

After I resolved my speed problems with Composer (see the post here ) I got this error once the Composer ended updating dependencies:

Fatal error: Call to undefined method Illuminate\Foundation\Application::getConfigLoader() in E:\path-to-my-project\vendor\laravel\framework\src\Illuminate\Foundation\start.php on line 106

As I already mentioned in my previous post I don’t know if this was due to me canceling composer updates several times or something else but the same error appeared when I opened my project URL in web browser.

The solution is simple: Delete bootstrap/compiled.php file.

After that run php artisan optimize command, which will generate new compiled.php file. I am not sure if this last step is necessary because everything seems to work even without the compiled.php file but I would advice to run this command just in case and regenerate compiled.php file.

Installing / updating Composer dependencies is very slow or time outs

I wanted to speed up my coding by adding Laravel 4 Generators and Laravel Artisan plugin for Sublime text 2 (you can learn more about this here). I added "way/generators": "dev-master" to my composer.json file as instructed and ran "php composer.phar update" and waited….and waited…and waited. How can downloading simple text files be so slow when I have very fast connection?

For some reason I always had problems with composers speed – installing or updating dependencies was very slow. By searching net I saw that a lot of people have similar problems and various solutions are offered – for some they work and for some they don’t. I would advise you to try them out and see if any of them help you.

One of the most common advices is to use the --prefer-dist switch:

php composer.phar update --prefer-dist

I ran it however it didn’t help me. Composer got stuck on updating symfony/filesystem dev-master. After 5 minutes I got this error:

[Symfony\Component\Process\Exception\RuntimeException]
The process timed-out.

After trying it few times with the same result I realized that git.exe was having some problems with my network (not sure what). So the problem seems to be with Git protocol, at least in my case. Composers default github-protocols config settings is ["git", "https", "http"]. So what I did was changed github-protocols to https with this command:

php composer.phar config -g github-protocols https

I ran the update again and it started working, much faster and no timeouts.

Note: I don’t know if this was due to me canceling composer updates several times but after composer finished updating I got this error for the first time :

Fatal error: Call to undefined method Illuminate\Foundation\Application::getConfigLoader()

The solution for this can be found here.

Google Sync Turned Off on my Android! How do I turn on Google Sync?

Yesterday I noticed that all my Google services were not being synced on my Nexus 7 (Android 4.2.2) anymore. Emails were not automatically downloaded, Calendar,Chrome, contacts etc were not updating. On top of that I was getting weird “Sync was unsuccessful” (or something like that) messages on my PC’s browser. Sure enough – sync was turned off on my Android tablet. For some reason option “turn on sync” is not easily accessible or at least not where you would expect it. If you go to Settings -> accounts then you will only be able to manually sync those accounts but not turn it on.

To turn on auto sync you have to go to

Settings -> Data usage -> Menu (top right corner, 3 small squares) -> check Auto-sync data

Here is the screenshot of the Menu:
turn on google sync auto-sync

How to remove horizontal scrollbar in Twitter Bootstrap tab function

While building my new admin/CMS with Laravel 4 and Gebo Admin (really cool twitter bootstrap responsive admin template) I encountered weird problem while using bootstrap tabs –  after I added “enhanced select” (Country dropdown) suddenly a horizontal scroll bar appeared!

How to remove horizontal scrollbar in tab function twitter bootstrap

I am not sure if this is 100% best solution (I am not that keen on digging into all this .js stuff) but the easiest way to fix this is to open Bootstrap.min.css, search for .tab-content and then replace

overflow: auto;

with

overflow: hidden;

Reload your page and the horizontal scrollbar is gone.

Enable Gmail Tabs – Tabbed Inbox

Gmail’s inbox Tabs are a very cool new Gmail feature that brings order to your inbox.

gmail inbox tabs

To enable it, click the gears button and try to find “Configure inbox”.

tabs inbox gmail

Click on “Configure inbox”, select the tabs that you wish to enable,click Save and you can now use the new feature.  In case you do not see “Configure inbox”, check back later.

ReflectionException: Class SomeClass does not exist – Laravel 4

Note: This post was written while Laravel 4 was still in beta.

When you add a new class (controller) in Laravel 4 you will most probably get

ReflectionException: Class SomeClass does not exist

SomeClass is of course the name of your new class.

Why does this happen? The file/controller is there, the class is there – it works in Laravel 3 so why doesn’t it work in Laravel 4?

The reason for this is that because of the performance reasons Laravel 4 (beta) has a static list of all classes that need to be autoloaded. Since you added your new controller Laravel doesn’t know about it yet. Hopefully this will be automated in the future but right now what you need to do is open your command prompt and type this (on Windows):

 >composer dump-autoload

If you get 'composer' is not recognized as an internal or external command error or Could not open input file: composer then use this version (also go to your project directory where composer.phar is located):

 >php composer.phar dump-autoload

Composer will (re)generate autoload files and your new controller will work.

Always displays battery icon in windows 7 system tray

How to move an icon (in my case I wanted to move battery icon) from that “hidden” system tray space so it will always be visible in system tray?

Simple, just click on the up arrow to display that “hidden” system tray area, grab the icon (hold the left mouse button) you would like to move and just move it to  the always-visible system tray area.

system tray windows 7
Pic: System tray on windows 7

Special message for P: this is to confirm my affiliation with the website – as requested by chat support

‘git’ is not recognized as an internal or external command

If you installed Git from windows.github.com you might get this error while running ‘git’ from windows command prompt(cmd):

‘git’ is not recognized as an internal or external command, operable program or batch file.

What you need to do is add Git path to Windows Environment Variables.

First, search for git.exe with windows search. You will find it in directory similar to this one:

C:\Users\user\AppData\Local\GitHub\PortableGit_76ds5d7f65adsf76as5f7as6f5asdf\bin

Add this to Windows Environment Variables :

  • right mouse-click “My Computer” and select “Properties”
  • if on Windows 7 then click on “Advanced system settings”,
  • open “Advanced” tab and click “Environment Variables”,
  • highlight/click on the “Path” variable under “System variables” and click “Edit”,
  • add your specific path to front of “Variable value” field or at the end, separated by a semicolon from the existing entry. Do not add a space between ; and last entry.Also, do not add ; after the last entry

Let say, just for example, that the Git.exe is in C:\Users\something\somefolder\bin folder. So when you edit your path variable it should look like this (thanks to my super Photoshop skills you can see that we are on Advanced tab, that we are editing Path variable and that I excel at making watermarks):

edit system variable git

Click Ok few times and try running Git again.

Warning: file_get_contents(): Unable to find the wrapper “https” – did you forget to enable it when you configured PHP?

I was installing Composer via CLI terminal for a new Laravel project and got this error:

Warning: file_get_contents(): Unable to find the wrapper “https” – did you forget to enable it when you configured PHP? in Command line code on line 1

The solution is easy: Open php.ini file (mine is located in xammp/php/php.ini ) and add (or uncomment) extension=php_openssl.dll in the list of Dynamic Extensions. Restart Apache and it should work.