Search Google

Monday 27 April 2015

[Tutorial] Installing & configuring laravel on shared hosting (Hostgator)

 




Connect to Hostgator's terminal using Putty or some other SSH tool. Once logged in, type 'pwd'. You should see something like this:
-jailshell$ pwd
/home2/CpanelUsername
This is where we want to install Laravel. But in order to do so, we must install Composer. However, Composer requires PHP 5.3.2+ to run. To check the PHP version, type 'php -v' (remember, the terminal PHP can be different from the PHP configuration for your website). Hopefully you'll see someting like this:
-jailshell$ php -v
PHP 5.5.6 (cli) (built: Dec  4 2013 13:50:26)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
PHP 5.5.6! You probably won't. In fact, you'll probably get PHP 5.2, just shy of the requirements to install composer and Laravel. In order to remedy this, create a new file called '.bashrc'. Kind of like .htaccess, the dot makes the file hidden. In the .bashrc file, put in the code:
alias php='/opt/php55/bin/php'
alias composer='/home2/CpanelUsername/composer.phar'
export PATH="/opt/php55/bin:$PATH"
Also, create a file called '.bash_profile'. In it, put:
[[ -s ~/.bashrc ]] && source ~/.bashrc
We've created several aliases. The php alias allows us to simply type 'php' instead of the lengthy '/opt/php55/bin/php' in order to access PHP 5.5. The composer alias allows us to type 'composer' instead of 'composer.phar' before every command. Also, since, we've created a direct path to it, composer.phar can be accessed anywhere, even if the file is not in the Laravel directory. The export PATH line allows Laravel to correctly path to the right PHP during its installation. Aliases do not apply during the installation process. Lastly, the bash_profile file makes it so that the .bashrc file fires up every time you start the linux console.
Upload both of them in your CpanelUsername directory, so it looks something like this:
CpanelUsername/
    access-logs/
    etc/
    perl5/
    public_html/
    tmp/
    www/
    .bash_history
    .bashrc        <-- here
    .bash_profile  <--here
Your directory may have more files and folders, and I've purposefully ommited the hidden ones. Now, you must activate the bash files. In your console, type: 'source ~/.bashrc' and then check your php version by typing 'php -v'.
-jailshell$ source ~/.bashrc
-jailshell$ php -v
PHP 5.5.6 (cli) (built: Dec  4 2013 13:50:26)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies
Awesome! We're good to go. Oh, while we're on the topic of PHP 5.5, we want to make an '.htaccess' file in our public_html folder. Create a file called '.htaccess' and write:
AddHandler application/x-httpd-php55 .php
This will enable PHP 5.5.6 on the website. Eventually, after we integrate Laravel's .htaccess, it should look something like this:
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

AddHandler application/x-httpd-php55 .php
Time to install Composer. In your terminal, type:
-jailshell$ curl -sS https://getcomposer.org/installer | php
The above process will download the necessary composer files in the current location. After that, install Laravel by running the following command:
-jailshell$ composer create-project laravel/laravel --prefer-dist
Now your directory should look something like this:
CpanelUsername/
    .composer/
    access-logs/
    etc/
    laravel/
    perl5/
    public_html/
    tmp/
    www/
    .bash_history
    .bashrc        
    .bash_profile 
    composer.phar
If you open the laravel folder, you'll see a folder structure like this:
CpanelUsername/
    .composer/
    access-logs/
    etc/
    laravel/
        app/
        bootstrap/
        public/
        ...
    perl5/
    public_html/
    tmp/
    www/
    .bash_history
    .bashrc        
    .bash_profile 
    composer.phar
You want to take the contents from the public folder and move them to the public_html folder. You can delete the public folder. It should look like this:
CpanelUsername/
    .composer/
    access-logs/
    etc/
    laravel/
    perl5/
    public_html/
        packages/
        .htaccess
        favicon.ico
        index.php
        robots.txt
    tmp/
    www/
    .bash_history
    .bashrc        
    .bash_profile 
    composer.phar
At this point, this starts to look a lot like Dries Vint's excellent guide. We are doing the first option. Anyway, open the 'laravel/bootstrap/paths.php' file and correct the bootstrap path like this:
28
29  'public' => __DIR__.'/../../public_html',
30
Do the same in 'public_html/index.php' and change the following lines:
20
21  require __DIR__.'/../laravel/bootstrap/autoload.php';
22

//

34
35  $app = require_once __DIR__.'/../laravel/bootstrap/start.php';
36
And that is it! Fire up your website and enjoy the lovely 'hello' screen :).

 

 

 

 

 

 

 

 

 

 

 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

Uploading your base files

Laravel has been designed so that you can keep your app files out of the public_html folder which adds extra security for your app. So what I suggest is that you create a folder in your root home directory, name it something like ‘app_base’, and put everything in there, assuming you have downloaded Laravel as a zip file from github. We will work on that folder for the next steps.
Your next option is to use git command via ssh. Hostgator has git installed for you.
login via ssh using the command bellow:
ssh -p 2222 username@server-ip-address
Once logged in, and you are in your root home folder, type git just to make sure you have it installed.
Next, clone the Laravel repository in the app_base folder using this code:
git clone https://github.com/laravel/laravel.git app_base
git will start downloading the framework for you.
Once finished, we are ready to install composer’s phar file. getComposer.org has a command line that you can use to download composer.phar into your app_base folder.
curl -sS https://getcomposer.org/installer | php
Obviously this won’t work, composer will tell you that it needs php 5.3.x to work.

PHP 5.3 is not used by default

Hostgator has php 5.3.7 installed on every shared hosting account. but to use it you need to do 2 small changes. The first is to add some code to your .htaccess file, and the second change is to use another command in your terminal to reference php 5.3.

Create an .htaccess file in your app_base folder

Yes you are right, there is no .htaccess in your app_base folder, but we will need to create one and add some code to it.
once created (And don’t forget the dot in front of htaccess), put this code in:
# Use PHP 5.3
AddType application/x-httpd-php53 .php

Using php 5.3

Now your app will be using php 5.3 instead of 5.2. but this is not everything, now when trying to use php in your terminal (or putty or whatever you are using) via SSH, you need to use/opt/php53/bin/php and it will work. Now let’s get back to install composer.
here is a little trick if you want to use php instead of/opt/php53/bin/php, add an alias:
alias php="/opt/php53/bin/php"

Installing Composer

Using ssh, cd into your app_base folder, and install composer using this code:
curl -sS https://getcomposer.org/installer | php
or
curl -sS https://getcomposer.org/installer | /opt/php53/bin/php
Composer will be installed without a problem if you followed all the steps from the beginning.
do a little ls just to verify that the composer.phar file is there.

Install the framework dependencies using composer

This is the fun part, all you have to do is shoot a composer install on your terminal, and every single package used by laravel will be downloaded and installed for you.
/opt/php53/bin/php composer.phar install
Or
php composer.phar install
If you notice that the last artisan command fails, don’t worry, you can run it yourself after composer is done installing.
The command is simply php artisan optimize
Now you have everything installed. Nothing will be accessible yet from the web. because we still need to move the public folder’s content to the public_html folder, so that you can point to that folder from the web.

Where to put things

Create a folder inside your public_html folder, name it say DEMO. And move the content of your laravel’s public folder into the demo folder.
If you point to the demo folder from the web, it won’t work. this is because you still need to update your paths.php file to include the correct paths to different parts of the application.

Update your public/index.php && paths.php files to include the correct paths

In order for the application to know where your App is, open the index.php file inside DEMO folder you created and change all the paths you find there. You need to provide valid paths to your bootstrap files.
change this:
require __DIR__.'/../bootstrap/autoload.php';
to
require __DIR__.'/../app_base/bootstrap/autoload.php';
And so on.
Now open your bootstrap folder inside your laravel app, and change the public path inside paths.php
Change this
'public' => __DIR__.'/../public'
to
'public' => __DIR__.'/../../public_html/demo'
If you got here, everything should work now, point your browser to your demo folder and see if your laravel app boots up with a default view saying YOU HAVE ARRIVED!
I hope this was helpful for you. let me know if you get stuck.


............................................

5 Platforms That Provide Free Django App Hosting

 http://learn2programming.blogspot.in/2015/04/python-cgi-setup-for-hostgator-hosting.html


I hope you’ll be able to find a free Django hosting platform that will suit your needs. They’re obviously not limited to Django only, and I’m only using the terminology so I can have the post rank for that keyword. That’s as transparent as it can get.

PythonAnywhere

PythonAnywhere
This is a cloud based platform – like most are – that allows you to have a server instance for all your Python development needs, and you can setup a fully functional web server within a couple of clicks. It currently supports one-click install for the following Python applications:
The list is too big to list here!
Head over to the ‘Batteries‘ page and see which libraries, frameworks and other Python tools are available for easy importation and installation.
The free plan offers enough specifications for you to do some basic testing, and even host a portfolio site if you’d like. You can upgrade to a ‘Hacker Plan’ at $5 per month, and that will allow you to have up to 10k visits per day, depending on the source and type of traffic.

Amazon AWS – Free

AWS Free Usage Tier
The Amazon AWS free plan is pretty much a way of learning more about the services that AWS & EC2 provide to the world, and perhaps get you hooked on the way their instances and system works in order to become a full-time customers. You’ll be able to do just about enough to get your feet wet with testing applications, and deploying them. It’s of course good to learn more about such platforms, as you never know when it might come in handy, especially when working in the field of development.
Serdar, an author on InfoWorld has recently published a quick review of the Amazon AWS Free plan and I’d love to have you check it out, as it goes more in-depth about the service and what you can expect.

OpenShift

OpenShift by Red Hat
This is a project maintained by the original Red Hat board, and provides a free – and paid – cloud service to those who need it. OpenShift is very popular in the community, and fully supports hundreds of applications and types of programming languages for you to launch from their ‘gears’.
Learn more about the pricing here.
The official OpenShift blog is full of tutorials, guides and other juicy information that will help you get going quickly. Most importantly, yes, it does support free Django hosting!

Heroku

Heroku - Cloud Application Platform
This platform is the perfect example of successful growth, over the last couple of years Heroku has become the place to go to when someone is looking to launch a new startup or a business. It provides incredibly cloud facilities and the server performance is really great, especially when it’s free!
It has now grown, and offers a ton of enterprise capabilities and plans for large companies that need infrastructure that can scale, we’re after Django hosting! You can head over to the Heroku’s own ‘Getting Started with Django‘ guide and learn how to setup a fully functional Django installation on your Heroku node.

Gondor

Gondor — Effortless Python Hosting from Idea to Launch
This is actually not a free platform / service, and will require a payment of $10 per month (cheap!) to have a server setup for you. It comes with a set of options you can choose from, in case you want to deploy different types of applications, see the pricing here.
I included Gondor because I know it’s being run by a team of Django developers, who love what they do and know their way around Django development very well, you can expect the highest quality service from some of the best there are.
check out the comment section for a chance to get $20 free credit from Gondor

Platforms for Free Django Hosting

Sunday 26 April 2015

Python CGI setup (for Hostgator hosting)

To install mod_wsgi in XAMPP Apache and serve Django (Windows) 

 

 

 



 DJANGO

In this post we will enable Python CGI for Hostgator
Create a .htaccess file and put following contents in this file:


This will make the web server to interprete .py file as Python CGI script.

Next create a python file (named test.py here) with following code:
And set this file’s permission setting so that Owner, Group and Public have “execute” permission for this file (Or set 755 permission simply)
Visit http://server_address/app_path/test.py, you will see a page with “hello” printed.

Perl and Python scripts

These scripts must have 755 permissions.
Perl = .pl
Python = .py
Example perl script:
#!/usr/bin/perl -w
print "Content-type: text/html\n\n";
print "<html><head>";
print "<title>CGI Test</title>";
print "</head><body>";
print "<p>Test page using Perl</p>";
print "</body></html>";
Example python script:
#!/usr/bin/python
print "Content-type: text/html\n\n";
print "<html><head>";
print "<title>CGI Test</title>";
print "</head><body>";
print "<p>Test page using Python</p>";
print "</body></html>";
Activate Python:
Please note that you have to add a line in the .htaccess file to use Python.
The recommended directive is:
Addhandler cgi-script .py .pl .cgi
(This directive covers Perl, Python and CGI files.)


Getting django up and running on hostgator

 

I thought it would be fun this year to start learning Django, so here’s a bit about how to get it set up using Hostgator (I have a shared hosting account).
I am using Terminal on the MAC and the File Manager on the cPanel.
The first thing you have to do is enable SSH (shell access). To do this, log into your cPanel and go to “Billing”:

Then choose, “View Hosting Packages”:

Then, click the link that says, “Enable Shell Access“.
Next, write down your IP as shown in the cPanel (I blurred mine out for security purposes, but you can see what the section looks like here):

Also, write down your cPanel username and password, you will need this.
Open Terminal and the File Manager in cPanel. I keep both open at the same time to see what I am doing.
In your File Manager, you should see /home/your-username/. Then look for a folder called django. You should have this. If not, in Terminal, type the following to SSH to your account:
ssh -p 2222 your-username-goes-here@your-ip-goes-here
If this works (you might have to wait a moment while it connects to your site), you will be prompted for your password.
Type in your password (you won’t see it at all) then hit enter and wait.
If this is your first time, you will be asked about a key. Just say “yes”.
You might then get some message like, “The authenticity of this host can’t be established” and “RSA key fingerprint is blah blah blah”.
Don’t worry about this, if you like, write down the key in case you need it later. That’s it. You are now connected to your logged in to your account via SSH. Now type the following.
mkdir ~/django
cd ~/django
svn co http://code.djangoproject.com/svn/django/trunk/django
mkdir creates a folder called “django”.
cd changes where you are to inside of the “django” folder.
The last line gets the latest stable version of django and installs it into the “django” folder. You need to have subversion installed for this to work.
I can’t really remember if I had to install subversion on my version of OS X, I think it was already installed, but if not, you’ll have to install it. It’s free.
Then, create a directory for your projects inside of the django folder by typing:
mkdir ~/django/projects
You should now have a folder called “django” with two folders inside:
Now, to test if django is running, you make a test project.
In Terminal, type:
cd projects
This will switch you into the projects folder.
Then type:
django-admin.py startproject newproject
This tells django to create a new project called, “newproject”.
Then type:
cd newproject
chmod +x manage.py
./manage.py startapp newapp

If you go inside of your “newproject” folder you should now see the following:

This is your “newapp”. Yay, django is working…sort of
Next, you have to enable fastcgi (or, I suppose, django will run really slowly).
Create a new file called index.fcgi in your public folder:

Then change the permissions of the file to 755:

Next, edit the file and add the following (be sure to change “username” with your username for your account):
#!/usr/local/bin/python
import sys, os, user

# sys.path.insert(0, "/usr/lib/python2.4")
sys.path.insert(0, "/home/your-username-goes-here/django")
sys.path.insert(0, "/home/your-username-goes-here/django/projects")
sys.path.insert(0, "/home/your-username-goes-here/django/projects/newproject")

# Switch to the directory of your project.
os.chdir("/homeyour-username-goes-here/django/projects/newproject")

# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ['DJANGO_SETTINGS_MODULE'] = "newproject.settings"

from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
Next, open the .htaccess that is in the same folder as index.fcgi.
AddHandler fcgid-script .fcgi
Options +FollowSymLinks
RewriteEngine On

RewriteRule (media/.*)$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(admin/.*)$ index.fcgi/$1 [L]
Next (and this is important) check your website. If you are getting a 500 error, open Terminal and log in to your account:
ssh -p 2222 your-username-goes-here@your-ip-goes-here
Then type:
which python
This should give you a message like:
/usr/bin/python
If you are getting something different (for example, user/local/bin/python/), update your script to reflect this:
#!/usr/local/bin/python
If all goes well, you should see this:

Below is my working code for hostgator
Below are my working code based on Robert code.
1. For curlgen.fcgi – change permission to 755
code is :
#!/usr/bin/python
import sys, os, user
# sys.path.insert(0, “/usr/lib/python2.7″)
sys.path.insert(0, “/home/r5tpl/django/projects”)
# Switch to the directory of your project.
os.chdir(“/home/r5tpl/django/projects/newproject”)
# Set the DJANGO_SETTINGS_MODULE environment variable.
os.environ[‘DJANGO_SETTINGS_MODULE’] = “newproject.settings”
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method=”threaded”, daemonize=”false”)
For .htaccess code is
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ curlgen.fcgi/$1 [QSA,L]

 

Sunday 19 April 2015

How does Python work?





Getting Django setup on Windows

A friend asked me how to setup an Django enviroment on Windows without the Cygwin fuzz. Here is the shortest steps I can think of:

1. Install Python3.4 as default path. (It should be "C:\Python34").
2. Open cmd.exe program on Windows and run the following commands:

    set PATH=%PATH%;C:\Python34;C:\Python34\Scripts
    pip install django
    python C:\Python34\Lib\site-packages\django\bin\django-admin.py startproject mysite
    cd mysite
    python manage.py syncdb

    (Follow prompts to setup an initial db. remember the user you used here.)

    python manage.py runserver

3. You are ready to django! Open your browser http://127.0.0.1:8000 to verify.
    Or login into http://127.0.0.1:8000/admin with the user you setup above.
  
What's next?
    Explore django with a guided tutorial here:
    https://docs.djangoproject.com/en/1.6/intro/tutorial01
 Learn Python in 5 min

http://www.quora.com/How-do-I-find-a-good-Django-tutorial-for-beginners

Installation

Via Laravel Installer

First, download the Laravel installer using Composer.
composer global require "laravel/installer=~1.1"
Make sure to place the ~/.composer/vendor/bin directory in your PATH (or C:\%HOMEPATH%\AppData\Roaming\Composer\vendor\bin if working with Windows) so the laravel executable is found when you run the laravel command in your terminal.
Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog would create a directory named blog containing a fresh Laravel installation with all dependencies installed. This method of installation is much faster than installing via Composer.

Via Composer

The Laravel framework utilizes Composer for installation and dependency management. If you haven't already, start by installing Composer.
Now you can install Laravel by issuing the following command from your terminal:
composer create-project laravel/laravel your-project-name --prefer-dist
This command will download and install a fresh copy of Laravel in a new your-project-name folder within your current directory.
If you prefer, you can alternatively download a copy of the Laravel repository from GitHub manually. Next run the composer install command in the root of your manually created project directory. This command will download and install the framework's dependencies.

Permissions

After installing Laravel, you may need to grant the web server write permissions to the app/storage directories. See the Installation documentation for more details on configuration.

Serving Laravel

Typically, you may use a web server such as Apache or Nginx to serve your Laravel applications. If you are on PHP 5.4+ and would like to use PHP's built-in development server, you may use the serve Artisan command:
php artisan serve
By default the HTTP-server will listen to port 8000. However if that port is already in use or you wish to serve multiple applications this way, you might want to specify what port to use. Just add the --port argument:
php artisan serve --port=8080

Directory Structure

After installing the framework, take a glance around the project to familiarize yourself with the directory structure. The app directory contains folders such as views, controllers, and models. Most of your application's code will reside somewhere in this directory. You may also wish to explore the app/config directory and the configuration options that are available to you.

Local Development Environment

In the past, configuring a local PHP development environment on your machine was a headache. Installing the proper version of PHP, required extensions, and other needed components is time consuming and confusing. Instead, consider using Laravel Homestead. Homestead is a simple virtual machine designed for Laravel and Vagrant. Since the Homestead Vagrant box is pre-packaged with all of the software you need to build robust PHP applications, you can create a virtualized, isolated development environment in seconds. Here is a list of some of the goodies included with Homestead:
  • Nginx
  • PHP 5.6
  • MySQL
  • Redis
  • Memcached
  • Beanstalk
Don't worry, even though "virtualized" sounds complicated, it's painless. VirtualBox and Vagrant, which are Homestead's two dependencies, both include simple, graphical installers for all popular operating systems. Check out the Homestead documentation to get started.

Routing

To get started, let's create our first route. In Laravel, the simplest route is a route to a Closure. Pop open the app/routes.php file and add the following route to the bottom of the file:
Route::get('users', function()
{
    return 'Users!';
});
Now, if you hit the /users route in your web browser, you should see Users! displayed as the response. Great! You've just created your first route.
Routes can also be attached to controller classes. For example:
Route::get('users', 'UserController@getIndex');
This route informs the framework that requests to the /users route should call the getIndex method on the UserController class. For more information on controller routing, check out the controller documentation.

Creating A View

Next, we'll create a simple view to display our user data. Views live in the app/views directory and contain the HTML of your application. We're going to place two new views in this directory: layout.blade.php and users.blade.php. First, let's create our layout.blade.php file:
<html>
    <body>
        <h1>Laravel Quickstart</h1>

        @yield('content')
    </body>
</html>
Next, we'll create our users.blade.php view:
@extends('layout')

@section('content')
    Users!
@stop
Some of this syntax probably looks quite strange to you. That's because we're using Laravel's templating system: Blade. Blade is very fast, because it is simply a handful of regular expressions that are run against your templates to compile them to pure PHP. Blade provides powerful functionality like template inheritance, as well as some syntax sugar on typical PHP control structures such as if and for. Check out the Blade documentation for more details.
Now that we have our views, let's return it from our /users route. Instead of returning Users! from the route, return the view instead:
Route::get('users', function()
{
    return View::make('users');
});
Wonderful! Now you have setup a simple view that extends a layout. Next, let's start working on our database layer.

Creating A Migration

To create a table to hold our data, we'll use the Laravel migration system. Migrations let you expressively define modifications to your database, and easily share them with the rest of your team.
First, let's configure a database connection. You may configure all of your database connections from the app/config/database.php file. By default, Laravel is configured to use MySQL, and you will need to supply connection credentials within the database configuration file. If you wish, you may change the driver option to sqlite and it will use the SQLite database included in the app/database directory.
Next, to create the migration, we'll use the Artisan CLI. From the root of your project, run the following from your terminal:
php artisan migrate:make create_users_table
Next, find the generated migration file in the app/database/migrations folder. This file contains a class with two methods: up and down. In the up method, you should make the desired changes to your database tables, and in the down method you simply reverse them.
Let's define a migration that looks like this:
public function up()
{
    Schema::create('users', function($table)
    {
        $table->increments('id');
        $table->string('email')->unique();
        $table->string('name');
        $table->timestamps();
    });
}

public function down()
{
    Schema::drop('users');
}
Next, we can run our migrations from our terminal using the migrate command. Simply execute this command from the root of your project:
php artisan migrate
If you wish to rollback a migration, you may issue the migrate:rollback command. Now that we have a database table, let's start pulling some data!

Eloquent ORM

Laravel ships with a superb ORM: Eloquent. If you have used the Ruby on Rails framework, you will find Eloquent familiar, as it follows the ActiveRecord ORM style of database interaction.
First, let's define a model. An Eloquent model can be used to query an associated database table, as well as represent a given row within that table. Don't worry, it will all make sense soon! Models are typically stored in the app/models directory. Let's define a User.php model in that directory like so:
class User extends Eloquent {}
Note that we do not have to tell Eloquent which table to use. Eloquent has a variety of conventions, one of which is to use the plural form of the model name as the model's database table. Convenient!
Using your preferred database administration tool, insert a few rows into your users table, and we'll use Eloquent to retrieve them and pass them to our view.
Now let's modify our /users route to look like this:
Route::get('users', function()
{
    $users = User::all();

    return View::make('users')->with('users', $users);
});
Let's walk through this route. First, the all method on the User model will retrieve all of the rows in the users table. Next, we're passing these records to the view via the with method. The with method accepts a key and a value, and is used to make a piece of data available to a view.
Awesome. Now we're ready to display the users in our view!

Displaying Data

Now that we have made the users available to our view, we can display them like so:
@extends('layout')

@section('content')
    @foreach($users as $user)
        <p>{{ $user->name }}</p>
    @endforeach
@stop
You may be wondering where to find our echo statements. When using Blade, you may echo data by surrounding it with double curly braces. It's a cinch. Now, you should be able to hit the /users route and see the names of your users displayed in the response.
This is just the beginning. In this tutorial, you've seen the very basics of Laravel, but there are so many more exciting things to learn. Keep reading through the documentation and dig deeper into the powerful features available to you in Eloquent and Blade. Or, maybe you're more interested in Queues and Unit Testing. Then again, maybe you want to flex your architecture muscles with the IoC Container. The choice is yours!

Deploying Your Application

One of Laravel's goals is to make PHP application development enjoyable from download to deploy, and Laravel Forge provides a simple way to deploy your Laravel applications onto blazing fast servers. Forge can configure and provision servers on DigitalOcean, Linode, Rackspace, and Amazon EC2. Like Homestead, all of the latest goodies are included: Nginx, PHP 5.6, MySQL, Postgres, Redis, Memcached, and more. Forge "Quick Deploy" can even deploy your code for you each time you push changes out to GitHub or Bitbucket!
On top of that, Forge can help you configure queue workers, SSL, Cron jobs, sub-domains, and more. For more information, visit the Forge website.
.........................................................................................................................................

All the Blade Template Commands

  • {{ $var }} – Echo content
  • {{ $var or 'default' }} – Echo content with a default value
  • {{{ $var }}} – Echo escaped content
  • {{-- Comment --}} – A Blade comment
  • @extends('layout') – Extends a template with a layout
  • @if(condition) – Starts an if block
  • @else – Starts an else block
  • @elseif(condition) – Start a elseif block
  • @endif – Ends a if block
  • @foreach($list as $key => $val) – Starts a foreach block
  • @endforeach – Ends a foreach block
  • @for($i = 0; $i < 10; $i++) – Starts a for block
  • @endfor – Ends a for block
  • @while(condition) – Starts a while block
  • @endwhile – Ends a while block
  • @unless(condition) – Starts an unless block
  • @endunless – Ends an unless block
  • @include(file) – Includes another template
  • @include(file, ['var' => $val,...]) – Includes a template, passing new variables.
  • @each('file',$list,'item') – Renders a template on a collection
  • @each('file',$list,'item','empty') – Renders a template on a collection or a different template if collection is empty.
  • @yield('section') – Yields content of a section.
  • @show – Ends section and yields its content
  • @lang('message') – Outputs message from translation table
  • @choice('message', $count) – Outputs message with language pluralization
  • @section('name') – Starts a section
  • @stop – Ends section
  • @endsection – Ends section
  • @append – Ends section and appends it to existing of section of same name
  • @overwrite – Ends section, overwriting previous section of same name\
.................................................................................................................
So to start.. we want to add/edit the content of our homepage. We can do this by going in to /app/routes.php. You will see that currently the route is hardcoded to return View::make('hello'). We could then simply change the view file.. but long term this just isn't going to fly. So comment this out (for the purpose of the tutorial - later you could remove completely) and add return HomeController::showWelcome(). You should now have something that looks like this:
1.Route::get('/', function()
2.{
3.return HomeController::showWelcome();
4.//return View::make('hello');
5.});
Now we're pointing the page to our controller HomeController... that you will find inside /app/controllers. We've now got better control on our content.
To start with now, we will set our logic inside the controller - but later in the tutorial we will move this in to a model.
Change your showWelcome method to this:
01.public static function showWelcome()
02.{
03. 
04.//$cheese = Test::getCheese();
05. 
06.$data   = array(
07. 
08.'cheese' => 'cheese value'
09.);
10. 
11.return View::make('hello', $data);
12.}
What is going on here?
OK.. so the first bit... ignore the commented out line for now.. we will come back to it.
The array called $data... this is where we can set all data that is passed to the view file. And you can see that for now I've hardcoded the value of 'cheese' to 'cheese value'... we will move this over to the model shortly.
Finally, we now tell the method to return a view, and we pass in to it our $data array.
If we go in to /app/views/hello.php now... you can add a echo $cheese; statement somewhere amongst the main html content (obviously wrapped in PHP tags). And now when you refresh yourdomain.com/public you should see the usual splash page.. but now with added cheese.
OK.. so we're in a much stronger position now... but now we want to ensure that our business logic is performed outside of the controller... as we don't want big fat ugly controllers.
We're now going to set it so that cheese value is returned from a model. So to start create a new file called Test.php inside of /app/models and then add this code to it:
01.class Test {
02. 
03. 
04.public static function getCheese() {
05. 
06.return "cheeeese";
07.}
08. 
09.}
Obviously in reality this would be a very poor method... but it's merely serving a point here. So this method returns a string of "cheeeese".
If we now go back to our controller HomeController.php, uncomment the uncommented line $cheese = Test::getCheese(); ... then change 'cheese value' to the var $cheese... like so:
1.$data   = array(
2. 
3.'cheese' => $cheese
4.);
If you refresh the page now you should see that our value is now coming in from our model.
That concludes this basic tutorial... obviously there is a lot more to learn about Laravel, but this tutorial at least (I hope) shows you how to setup a very basic page in Laravel.
Thanks for reading!

.............................................................................................
This tutorial will walk us through:
  • Creating a users table using migrations
  • Filling our new users table with sample users using seeding
  • Using the great artisan command line tool to migrate and seed
  • Creating a login form and processing a login using routes, controllers, and views
  • Handling login errors
  • Use Eloquent ORM to validate a user

Getting our Database Ready

To get our authentication working, we will need to have a database and users to login with.

Database Setup

Set up your database and user. Assign that user to the database and make sure you update your settings in app/config/database.php.

Migrations

Migrations are a way we can manipulate our database within our codebase. This means we don’t have to get our hands dirty by doing any SQL commands or messing around inside a tool like phpmyadmin. For more information and the benefits of migrations, see the official docs.
Migrations are very easy to create. The easiest way to create a migration will be to use the great artisan command line interface created by Taylor Otwell. To create the migration, via the command line, in the root folder of your application, simply type:
php artisan migrate:make create_users_table ––create=users
This will automatically create a migrations file inside of your app/database/migrations folder. Let’s take a look at the newly created file.
// app/database/migrations/####_##_##_######_create_users_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
      Schema::create('users', function(Blueprint $table)
      {
          $table->increments('id');
          $table->timestamps();
      });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
      //
  }

}

Laravel generates the core of the migration file for you and the –create command will let the migration create the table for you. It will create a table for you with an id field and the timestamps field. This will make created_at and updated_at fields. Now we use the Schema Builder to create our users table.
// app/database/migrations/####_##_##_######_create_users_table.php

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
      Schema::create('users', function(Blueprint $table)
      {
          $table->increments('id');

          $table->string('name', 32);
          $table->string('username', 32);
          $table->string('email', 320);
          $table->string('password', 64);

                      // required for Laravel 4.1.26
                      $table->string('remember_token', 100)->nullable();
          $table->timestamps();
      });
  }

  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
      Schema::drop('users');
  }

}

Now this migration file will be responsible for creating the users table and also destroying it if needed. To run the migration and create our user table, use the command line again and run:
php artisan migrate
Just like that, the command will use the up() function and bam! We have our users table with all the columns we wanted.
Reverting Migrations: Now if you wanted to rollback migrations, we could use php artisan migrate:rollback or php artisan migrate:reset.
Now that we have our table, lets create sample users.

Seeding

Seeding is the technique of filling our database with sample data so we can test and create our applications. It really does make building applications much easier. For seeder files, we won’t be using artisan. We’ll make these the good old fashioned way… New file. In your app/database/seeds folder, create a file called UserTableSeeder.php.
// app/database/seeds/UserTableSeeder.php

<?php

class UserTableSeeder extends Seeder
{

public function run()
{
    DB::table('users')->delete();
    User::create(array(
        'name'     => 'Chris Sevilleja',
        'username' => 'sevilayha',
        'email'    => '',
        'password' => Hash::make('awesome'),
    ));
}

}

We will create a user and all of the above is pretty self explanatory aside from password. We will use Laravel’s Hash class to create a secure Bcrypt hashing of our password. This is always a good practice to hash our password and to read more about Laravel security, check out the docs. Now that we have created our file, we need to Laravel to call it. Inside the app/database/seeds/DatabaseSeeder.php, add the line $this->call('UserTableSeeder');.
// app/database/seeds/DatabaseSeeder.php

<?php

class DatabaseSeeder extends Seeder {

  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run()
  {
      Eloquent::unguard();

      $this->call('UserTableSeeder');
  }

}

Once we’re done with our seeder file, we can inject that user into our database using:
php artisan db:seed

The Application

Now that we have a database, a table thanks to migrations, and a user thanks to seeding, we can build the authentication system. We will need to create routes, controllers, and views for our form.

Routes

In Laravel, our routes file dictates the lay of the land in our application. We will define 2 routes for our login, one for the http get to show the form, and one for the http post request to process the form. Laravel let’s us define routes based on HTTP request types and this helps to organize our application and how a user interacts around the site. For more info on this: show link. Add the following routes we need in our app/routes.php file:
// app/routes.php

<?php

// route to show the login form
Route::get('login', array('uses' => ''));

// route to process the form
Route::post('login', array('uses' => ''));

Now if we go to our application in our browser and go to www.example.com/login, we will get an error because we haven’t defined the HomeController@showLogin function yet. Let’s do that.

Controller

In our app/controllers directory, Laravel should already come with a HomeController.php and a BaseController.php. Inside our HomeController.php, we are going to create the two functions we need. Add these two.
// app/controllers/HomeController.php<

...

public function showLogin()
{
    // show the form
    return View::make('login');
}

public function doLogin()
{
// process the form
}
For now, we will only deal with the function to show the form.

View

The easiest part of this process will be creating our login view. In the app/views folder, create a file called login.blade.php. The .blade.php extension lets Laravel know that we will be using its Blade Templating system.
<!-- app/views/login.blade.php --><

<!doctype html>
<html>
<head>
<title>Look at me Login</title>
</head>
<body><

{{ Form::open(array('url' => 'login')) }}
<h1>Login</h1>

<!-- if there are login errors, show them here -->
<p>
    {{ $errors->first('email') }}
    {{ $errors->first('password') }}
</p>

<p>
    {{ Form::label('email', 'Email Address') }}
    {{ Form::text('email', Input::old('email'), array('placeholder' => '')) }}
</p>

<p>
    {{ Form::label('password', 'Password') }}
    {{ Form::password('password') }}
</p>

<p>{{ Form::submit('Submit!') }}</p>
{{ Form::close() }}

When someone submits the form, it posts to the HomeController@doLogin function. Let’s validate the information and process the form.
If there are validation errors, they will be redirected here and the email input will already be filled in with their old input. Errors will also show if there are any.

Processing the Form

Back in our HomeController.php, let’s build out our doLogin() function. We have to validate the information sent to make sure that we have an email and a password. Both fields are required.
// app/controllers/HomeController.php<


public function doLogin()
{
// validate the info, create rules for the inputs
$rules = array(
    'email'    => 'required|email', // make sure the email is an actual email
    'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
);

// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);

// if the validator fails, redirect back to the form
if ($validator->fails()) {
    return Redirect::to('login')
        ->withErrors($validator) // send back all errors to the login form
        ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
} else {

    // create our user data for the authentication
    $userdata = array(
        'email'     => Input::get('email'),
        'password'  => Input::get('password')
    );

    // attempt to do the login
    if (Auth::attempt($userdata)) {

        // validation successful!
        // redirect them to the secure section or whatever
        // return Redirect::to('secure');
        // for now we'll just echo success (even though echoing in a controller is bad)
        echo 'SUCCESS!';

    } else {        

        // validation not successful, send back to form 
        return Redirect::to('login');

    }

}
}
We use the Auth class to authenticate a user. Auth::attempt() will check the plaintext password against the hashed password we saved in our database.
Try the login: Let’s try to login with whatever we put in our app/database/UserTableSeeder.php file. In our case:
Email Password
chris@scotch.io awesome
If the authentication is successful (Auth::attempt() returns true), we will redirect the user to wherever they should go. After they are logged in, that users information is saved and can be accessed using Auth::user()->email;. If the authentication is not successful, we will be kicked back to the login form with errors and the old email input to populate the form.

Logout

Logging out is a simple matter. We’ll need a new route and a new function.
Add this route for logout.
// app/routes.php
...
Route::get('logout', array('uses' => ''));
...
 
Ideally, this route would be a POST route for security purposes. This will ensure that your logout won’t be accidentally triggered. http://stackoverflow.com/questions/3521290/logout-get-or-post Also, to handle this as a POST, you will have to handle your link differently. You’ll have to create a POST request to your logout route.
For logout, we will flush and clean out the session and then redirect our user back to the login screen. You can change this to redirect a user wherever you would like. A home page or even a sad goodbye page.
// app/controllers/HomeController.php
public function doLogout()
{
    Auth::logout(); // log the user out of our application
    return Redirect::to('login'); // redirect the user to the login screen
}
 
Now that you have the route and the function, you can create a logout button by using the Laravel URL helper.
<!-- LOGOUT BUTTON -->
<a href="{{ URL::to('logout') }}">Logout</a>
 

Bam!

Now going to your login page, www.example.com/login and submitting the login form will provide validation, authentication against a user in the database, and a little more understanding of how Laravel makes things like building an authentication system easier. We’ll be doing a lot more writeups on Laravel, so sound off in the comments if you have questions or anything else you want to see.
Edit Updated the doLogin() function and the view to pass back errors and handle Auth correctly with Hash::check(). Edit #2 Changed back to the Auth::attempt() login method. Edit #3 Cleaned up and commented code examples. Provided code for download. Edit #4 Added logout. Edit #5 Upgraded user migration to work with Laravel 4.1.26 
----------------------------------------------------------------

Q.....This question may seems a little bit silly, but what the heck.
I started to learn Python. I know basic syntax, etc.
When I work with HTML, PHP, etc., I simply write code, put it inside .html or .php file and double click this file. Then my code runs. I can work with databases and other stuff - it's just simple. But how does Python work? I'm working inside Eclipse or Python command line and I can run this code, but what if I want make website with Python for example?
I don't think it's like I put .py file on my server, so what I need to do? I understand I need to install Python on my webserver through some server command line (I've never used it, but I will find some tutorials day I will need it) but what's next? How can I combine my Python knowledge with HTML, CSS, PHP, etc.?
Python may also be used to create desktop apps, what then? Can I export .exe file with Python code or what?
Any links with content describing my concerns are welcome!

 http://programmers.stackexchange.com/questions/107922/how-does-python-work
ANS.................

When I work with HTML, PHP, etc., I simply write code, put it inside .html or .php file and double click this file. Then my code runs.
But how does Python work?
Exactly the same way.
Double-click a .py file and your code runs.
I'm working inside Eclipse or Python command line and I can run this code, but what if I want make website with Python for example?
You usually use Apache to host a web site. You usually use mod_wsgi to run Python inside Apache. This is exactly like using mod_php to run PHP inside Apache.
Exactly the same.
I don't think it's like I put .py file on my server,
False. You do put .py files on your server. How else could it possibly work?
so what I need to do? I understand I need to install Python on my webserver through some server command line (I've never used it, but I will find some tutorials day I will need it) but what's next?
You need mod_php to run PHP. You need mod_wsgi to run Python.

So if I made some website with Python, then my user will see my index.py file when he comes to my server?
You could do that. It would be fairly silly, however.
Usually, you set up mod_wsgi so that it executes your .py file, and your .py file creates the HTML page.
This parallels the way mod_php executes the .php file to create an HTML page.
Or can I use Python code inside html like with php wrapped inside <?php ?>?
No. You put the HTML inside the Python.


How can I combine my Python knowledge with html, css, php etc?
Use a web framework that supports Python, such as Django.
Python may also be used to create desktop apps, what then? Can I export .exe file with Python code or what?
Python is typically executed by an interpreter, so it's easy to use interactively and you can see results of your changes almost immediately. A Python program can also be packaged up into a stand-alone executable; more on how to do that here.


Django is a free web framework written in python. It's very to use!

Let's create a blog in less then 10min!

1. First create a project

django-admin.py startproject blog

Switch to folder "blog"

Start the dev server

./manage runserver 8000

Type: http://127.0.0.1:8000 in browser


2. Create a file "models.py"

 Create a model

from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=32)
    date = models.DateTimeField(auto_now_add=True)
    text = models.TextField()

3. Setup your database settings

Edit the file "settings.py"

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'test',                      # Or path to database file if using sqlite3.
        'USER': 'test',                      # Not used with sqlite3.
        'PASSWORD': 'password',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

4. "Install" the blog models

Add "blog" to INSTALLED_APPS

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog', #<-------------------------------
    # Uncomment the next line to enable the admin:
    #'django.contrib.admin',
)

5. Create a templates

Create folder "templates".

Switch to folder "templates". Create file "index.html"

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
    {% endblock %}
    </div>
</body>

</html
6. Setup the templates path
Edit "settings.py" file.
Import os at the top
Add path to TEMPLATES_DIRS
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__),'templates'), # creates a absolute path
)

7. Create the blog tables

Run "./manage syncdb"

It will create the blog tables.
It will ask you to create a superuser, follow the instructions

8. Add a url pattern

Edit file "urls.py"

urlpatterns = patterns('',
    # Example:
    # (r'^blog/', include('blog.foo.urls')),
    (r'^, 'blog.views.index'), #<------------------- index/root entry

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    #(r'^admin/', include(admin.site.urls)),
)

9. Create a view

Create a file "views.py"
from django.shortcuts import render_to_response

def index(request):
    return render_to_response('index.html', locals())

Run the dev server: ./manage runserver 8000


10. Activate the admin

Uncomment "django.contrib.admin" in INSTALLED_APPS
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'blog',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin', #<<<------- uncommented
)

Edit "urls.py" file

from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
from django.contrib import admin #<<< uncomment this
admin.autodiscover() #<<< uncomment this

urlpatterns = patterns('',
    (r'^, 'blog.views.index'),
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)), #<<< uncomment this
)

Run ./manage syncdb

11. Activate the module in admin

Create file "admin.py"

from django.contrib import admin
from blog.models import Blog

class AdminBlog(admin.ModelAdmin):
    pass

admin.site.register(Blog, AdminBlog)

Type "http://127.0.0.1:8000/admin" in your browser

Login as superuser which you choose before


Click on "Add" and create some posts

12. Fill the view with logic

from django.shortcuts import render_to_response
from blog.models import Blog

def index(request):
    entries = Blog.objects.all()
    return render_to_response('index.html', locals())

13. Show it in template

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>My Blog</title>
    </head>

<body>
    <div id="content">
    {% block content %}
        {% for e in entries %}
            {{ e.title }}<br/>
            {{ e.date }}<br/>
            {{ e.text }}<br/>
            <hr/>
        {% endfor %}

    {% endblock %}
    </div>
</body>

</html>
Type http://127.0.0.1:8000 in your browser and you see your blog!

We are done!