Monday, 3 February 2014

Tutorial on how to store images in Mysql BLOB field

mysql
mysql
Sometimes in our web application we need the image upload feature. User can browse an image from his/her PC and clicks the upload/submit button to upload this image to the server. Basically this happens when we create web applications like photo gallery or user avatar selection etc.
There are two ways uploaded images can be stored in server- In server’s physical directory or in the database. Storing in physical directory is like copying the image from user’s machine to server directory. The advantage is that it only takes spaces from the server’s physical directory. But disadvantage is the extra headache of taking backup for website administrator. In database we can store the images easily and taking backup of database is sufficient. But here the disadvantage is that large volume of data might slow down the database operation.
In this tutorial we’ll discuss about image upload in mysql database and how to display it. In MySQL images or any files can be stored in a specific field called BLOB (Basic Large Object or Binary Large Object). BLOB fields are designed to store any binary files. There are 4 types of BLOB fields are available in MySQL: TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB. The descriptions are self explanatory.
In our sample PHP-MySQL code we’ll use only BLOB field. So open your phpmyadmin and execute this SQL to create the table.
CREATE TABLE `img_tbl` (
 `id` INT(4) NOT NULL AUTO_INCREMENT,
 `img_name` VARCHAR(255) COLLATE latin1_general_ci NOT NULL,
 `img_type` VARCHAR(4) COLLATE latin1_general_ci NOT NULL,
 `img_size` INT(8) NOT NULL,
 `img_data` BLOB NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;


`id` is the unique id for the table row. This is the primary key. `img_name` field stores the image name. `img_type` stores the information about the type of images like JPG or GIF etc. `img_size` holds the size of the image and img_data stores the actual image file.
Now we need a HTML file which will allow the user to browse and select the image to upload. Elow is the code snippet for this:
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> Image Upload to BLOB field </TITLE>
</HEAD>
 
<BODY>
<FORM NAME=”f1″ METHOD=”POST” ACTION=”upload.php” ENCTYPE=”multipart/form-data”>
<table>
<tr><td> Image Upload Page </td></tr>
<tr><td> <input type=”file” name=”imgfile”/></td></tr>
<tr><td> <input type=”submit” name=”submit” value=”Save”/> </td></tr>
</table>
</FORM>
</BODY>
</HTML>
Remember always put the ENCTYPE attribute to be “multipart/form-data” to make it post files to the server. If you forget to add this attribute in the HTML <form /> tag, then no files will be posted to the server. The HTML element that displays the file select dialog box to the user is the tag <input type=”file” name=”imgfile” />. When user submits the selected image to upload to the server the control goes to the PHP script upload.php which handles the upload of the image file to the server. The code snippet of upload.php is given below:
upload.php
<?
include “dbconfig.php”;
 
$dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die(”Error Occurred-.mysql_error());
mysql_select_db($dbname, $dbconn) or die(”Unable to select database”);
 
if(isset($_REQUEST[submit]) && $_FILES[imgfile][size] > 0)
{
          $fileName       = $_FILES[imgfile][name]; // image file name
          $tmpName     = $_FILES[imgfile][tmp_name]; // name of the temporary stored file name
          $fileSize           = $_FILES[imgfile][size]; // size of the uploaded file
          $fileType         = $_FILES[imgfile][type]; // file type
 
          $fp                    = fopen($tmpName, ‘r’); // open a file handle of the temporary file
          $imgContent  = fread($fp, filesize($tmpName)); // read the temp file
          fclose($fp); // close the file handle
 
          $query = “INSERT INTO img_tbl (`img_name`, `img_type`, `img_size`, `img_data` )
                        VALUES ($fileName’,$fileType’,$fileSize’,$imgContent’);
 
          mysql_query($query) or die(’Error, query failed’);
          $imgid = mysql_insert_id(); // autoincrement id of the uploaded entry
          mysql_close($dbconn);
 
          echo "<br>Image successfully uploaded to database<br>";
          echo "<a href=\”viewimage.php?id=$imgid\”>View Image</a>";
 
}else die(”You have not selected any image”);
?>
dbconfig.php
<?
  $dbhost           =             “localhost”; // server host name
  $dbusr            =              “root”; // mysql username to connect
  $dbpass           =             “”; //password
  $dbname           =            ”compass”; //database name to select to
?>
Let me explain the script step by step. dbconfig.php script contains the database connection information like host name, userid and password and database name to select. The script upload.php first includes the dbconfig.php in order to include the database information because we’ll be executing the SQL to insert the uploaded image file into the database BLOB field.

$_FILES is the global variable which is created by PHP itself to hold the information about the uploaded file object. First the uploaded image is stored as a temp file in the temp folder of the server. The temp name can be retrieved from $_FILES[imgfile][tmp_name]. Now the temp image is read and stored in the BLOB field.


The next script will show you how you can download the image from the BLOB field of the MySQL database and display to the browser.
showimages.php
<?
    include “dbconfig.php”;
    $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die(”Error Occurred-.mysql_error());
    mysql_select_db($dbname, $dbconn) or die(”Unable to select database”);
 
    $query = “SELECT `id`, `img_name`, `img_type`, `img_size`, `img_data`
                     FROM img_tbl ORDER BY `id`”;
 
    $result = mysql_query($query) or die(’Error, query failed’);
 
    while($row = mysql_fetch_array($result)){
               echo<img src=\”viewimage.php?id=$row[id]\” width=\”55\” height=\”55\” /> <br/>;
    }
 
    mysql_close($dbconn);
?>
This script is actually fetching all the data from database and printing the images in the <img src=””/> tag. So the content is written to the browser by the viewimage.php script.

viewimage.php
<?
if(isset($_REQUEST['id']))
{
   // get the file with the id from database
      include “dbconfig.php”;
      $dbconn = mysql_connect($dbhost, $dbusr, $dbpass) or die(”Error Occurred-.mysql_error());
      mysql_select_db($dbname, $dbconn) or die(”Unable to select database”);
 
      $id    = $_ REQUEST ['id'];
      $query = “SELECT `img_name`, `img_type`, `img_size`, `img_data`
                       FROM img_tbl WHERE id =$id’”;
 
      $result = mysql_query($query) or die(mysql_error());
      list($name, $type, $size, $content) = mysql_fetch_array($result);
 
      header(”Content-length: $size”);
      header(”Content-type: $type”);
      print $content;
 
      mysql_close($dbconn);
}
?>

In this script the header () function is playing an important role. This function actually tells the browser what to do with the BLOB content. It takes several parameters like size, type etc. “Content-length” sets the size of the file, and “Content-type” sets the type of the file (JPG or GIF or PNG etc.). After setting the header, the actual BLOB content is written using print $content. The <img src=”” /> tag then is able to display the images.

Monday, 13 January 2014

The two ways of iterating through arrays

void list ( mixed ...)
array each ( array input)
If you do not specify a key, as in the first example, PHP will just assign incrementing numbers starting with 0. However, these numbers cannot be guaranteed to exist within the array in any given order, or even to exist at all - they are just key values themselves. For example, an array may have keys 0, 1, 2, 5, 3, 6, 7. That is, it can have its keys out of order or entirely missing. As a result, code like this should generally be avoided:
<?php
    
for ($i = 0; $i < count($array); ++$i) {
        print
$array[$i];
    }
?>
However, there is a quick and easy way to accomplish the same thing: a foreach loop, which itself has two versions. The easiest way to use foreach looks like this:
foreach($array as $val) {
    print
$val;
}
Here the array $array is looped through and its values are extracted into $val. In this situation, the array keys are ignored completely, which usually makes most sense when they have been auto-generated (i.e. 0, 1, 2, 3, etc).
The second way to use foreach does allow you to extract keys, and looks like this:
foreach ($array as $key => $val) {
    print
"$key = $val\n";
}
Another commonly used way to loop over arrays is using the list() and each() functions, like this:
<?php
    
while (list($var, $val) = each($array)) {
        print
"$var is $val\n";
    }
?>
List() is a function that does the opposite of array() - it takes an array, and converts it into individual variables. Each() takes an array as its parameter, and returns the current key and value in that array before advancing the array cursor. "Array cursor" is the technical term for the element of an array that is currently being read. All arrays have a cursor, and you can freely move it around - it is used in the while loop above, where we need to iterate through an array. To start with, each() will return the first element, then the second element, then the third, and so on, until it finds there are no elements left, in which case it will return false and end the loop.
The meaning of that first line is "get the current element in the array, and assign its key to $var and its value to $val, then advance the array cursor. There is a lot more detail on array cursors later.
Generally speaking, using foreach loops is the most optimised way to loop through an array, and is also the easiest to read. In practice, however, you will find foreach loops and list()/each() loops in about equal proportions, despite the latter option being slower. The key difference between the two is that foreach automatically starts at the front of the array, whereas list()/each() does not.

Monday, 14 October 2013

10 PHP code snippets for working with strings


Strings are a very important kind of data, and you have to deal with them daily with web development tasks. In this article, I have compiled 10 extremely useful functions and code snippets to make your php developer life easier.

Automatically remove html tags from a string

On user-submitted forms, you may want to remove all unnecessary html tags. Doing so is easy using the strip_tags() function:
$text = strip_tags($input, "");
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Get the text between $start and $end

This is the kind of function every web developer should have in their toolbox for future use: give it a string, a start, and an end, and it will return the text contained with $start and $end.
function GetBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}
Source: http://www.jonasjohn.de/snippets/php/get-between.htm

Transform URL to hyperlinks

If you leave a URL in the comment form of a WordPress blog, it will be automatically transformed into a hyperlink. If you want to implement the same functionality in your own website or web app, you can use the following code:
$url = "Jean-Baptiste Jung (http://www.webdevcat.com)";
$url = preg_replace("#http://([A-z0-9./-]+)#", '$0', $url);
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=2

Split text up into 140 char array for Twitter

As you probably know, Twitter only accepts messages of 140 characters or less. If you want to interact with the popular social messaging site, you’ll enjoy this function for sure, which will allow you to truncate your message to 140 characters.
function split_to_chunks($to,$text){
 $total_length = (140 - strlen($to));
 $text_arr = explode(" ",$text);
 $i=0;
 $message[0]="";
 foreach ($text_arr as $word){
  if ( strlen($message[$i] . $word . ' ') <= $total_length ){
   if ($text_arr[count($text_arr)-1] == $word){
    $message[$i] .= $word;
   } else {
    $message[$i] .= $word . ' ';
   }
  } else {
   $i++;
   if ($text_arr[count($text_arr)-1] == $word){
    $message[$i] = $word;
   } else {
    $message[$i] = $word . ' ';
   }
  }
 }
 return $message;
}
Source: http://www.phpsnippets.info/split-text-up-into-140-char-array-for-twitter

Remove URLs from string

When I see the amount of URLs people try to leave in my blog comments to get traffic and/or backlinks, I think I should definitely give a go to this snippet!
$string = preg_replace('/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);
Source: http://snipplr.com/view.php?codeview&id=15236

Convert strings to slugs

Need to generate slugs (permalinks) that are SEO friendly? The following function takes a string as a parameter and will return a SEO friendly slug. Simple and efficient!
function slug($str){
 $str = strtolower(trim($str));
 $str = preg_replace('/[^a-z0-9-]/', '-', $str);
 $str = preg_replace('/-+/', "-", $str);
 return $str;
}
Source: http://snipplr.com/view.php?codeview&id=2809

Parse CSV files

CSV (Coma separated values) files are an easy way to store data, and parsing them using PHP is dead simple. Don’t believe me? Just use the following snippet and see for yourself.
$fh = fopen("contacts.csv", "r");
while($line = fgetcsv($fh, 1000, ",")) {
    echo "Contact: {$line[1]}";
}
Source: http://phpbuilder.com/columns/Jason_Gilmore060210.php3?page=1

Search for a string in another string

If a string is contained in another string and you need to search for it, this is a very clever way to do it:
function contains($str, $content, $ignorecase=true){
    if ($ignorecase){
        $str = strtolower($str);
        $content = strtolower($content);
    }
    return strpos($content,$str) ? true : false;
}
Source: http://www.jonasjohn.de/snippets/php/contains.htm

Check if a string starts with a specific pattern

Some languages such as Java have a startWith method/function which allows you to check if a string starts with a specific pattern. Unfortunately, PHP does not have a similar built-in function.
Whatever- we just have to build our own, which is very simple:
function String_Begins_With($needle, $haystack {
    return (substr($haystack, 0, strlen($needle))==$needle);
}
Source: http://snipplr.com/view.php?codeview&id=2143

Extract emails from a string

Ever wondered how spammers can get your email address? That’s simple, they get web pages (such as forums) and simply parse the html to extract emails. This code takes a string as a parameter, and will print all emails contained within. Please don’t use this code for spam ;)
function extract_emails($str){
    // This regular expression extracts all emails from a string:
    $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i';
    preg_match_all($regexp, $str, $m);

    return isset($m[0]) ? $m[0] : array();
}

$test_string = 'This is a test string...

        test1@example.org

        Test different formats:
        test2@example.org;
        <a href="test3@example.org">foobar</a>
        <test4@example.org>

        strange formats:
        test5@example.org
        test6[at]example.org
        test7@example.net.org.com
        test8@ example.org
        test9@!foo!.org

        foobar
';

print_r(extract_emails($test_string));
Source: http://www.jonasjohn.de/snippets/php/extract-emails.htm

Sunday, 1 September 2013

DocBlox ... use to generate API documentation in PHP

Using DocBlox

Until a few years ago, there were basically two tools you could use to generate API documentation in PHP: phpDocumentor and Doxygen. phpDocumentor was long considered the standard, with Doxygen getting notice when more advanced features such as inheritance diagrams are required. However, phpDocumentor is practically unsupported at this time (though a small group of developers is working on a new version), and Doxygen has never had PHP as its primary concern. As such, a number of new projects are starting to emerge as replacements.
One of these is DocBlox. I am well aware there are several others -- and indeed, I've tried several of them. This post is not here to debate the merits or demerits of this or other solutions; the intention is to introduce you to DocBlox so that you can evaluate it yourself.

Getting DocBlox

DocBlox can be installed in a variety of ways:
I personally prefer using the PEAR installer, as it's as simple as this:

prompt> pear channel-discover pear.michelf.com
prompt> pear channel-discover pear.docblox-project.org
prompt> pear install -a docblox/DocBlox-beta
The first channel-discover is to grab a third-party package optionally used in the rendering process to convert Markdown in the descriptions to HTML. And don't let the "beta" status fool you -- this project is quite stable at this point; the author, Mike van Riel, is simply being conservative as he rounds out features.
If you are checking out the project via Git or a snapshot, you simply need to expand the archive and make a note of its location -- when I've used this method in the past, I usually create a symlink to the bin/docblox.php script in my path:

prompt> ln -s path/to/docblox/bin/docblox.php ~/bin/docblox

Using DocBlox

Once you have installed DocBlox, how do you use it? It's really quite easy:

prompt> cd some/project/of/yours/
prompt> mkdir -p documentation/api/
prompt> docblox run -d path/to/source/ -t documentation/api/
At this point, DocBlox will merrily scan your source located in path/to/source, and build API documentation using its default HTML templates for you in documentation/api. Once complete, you can point your browser at documentation/api/index.html and start browsing your API documentation.

Using DocBlox to identify missing docblocks

While running, you may see some notices in your output stream, like the following:
2011-08-02T16:08:34-05:00 ERR (3): No DocBlock was found for Property $request in file Mvc/Route/RegexRoute.php on line 16
This output is invaluable for identifying places you've omitted docblocks in your code. You can capture this information pretty easily using tee:

prompt> docblox run -d path/to/source/ -t documentation/api/ 2>&1 | tee -a docblox.log
I recommend doing this whenever running DocBlox, going through the output, and adding docblocks wherever you encounter these errors.
(You can do similarly using tools such as PHP_CodeSniffer. More tools is never a bad thing, though.)
If you want to disable the verbosity, however, you can, by passing either the -q or --quiet options.

Class Diagrams

DocBlox will try and generate class diagrams by default. In order to do this, you need to have GraphViz installed somewhere on your path. The results are pretty cool, however -- you can zoom in and out of the diagram, and click on classes to get to the related API documentation.
(The class diagram is typically linked from the top of each page.)

Specifying an alternate title

By default, DocBlox uses its own logo and name as the title of the documentation and in the "header" line of the output. You can change this using the --title switch:

prompt> docblox run -d path/to/source/ -t documentation/api/ --title \"My Awesome API Docs\"

Using alternate templates

While the default template of DocBlox is reasonable, one of its initial selling points to me was the fact that you could conceivably create new templates. In order to test this out, and also iron out some of the kinks, Mike wrote templates for a few PHP OSS projects, including Zend Framework and Agavi. Templates need to be in a location DocBlox can find them -- in DocBlox/data/themes under your PEAR install, or simply data/themes if you installed a release tarball. Invoking a theme is as easy as using the --template argument:

prompt> docblox run -d path/to/source/ -t documentation/api/ --title \"My Awesome API Docs\" --template zend
Try out each of the provided themes to see which you might like best -- and perhaps try your hand at writing a theme. Each given theme is simply an XML file and a small set of XSL stylesheets, and optionally CSS and images to use with the generated markup.

Iterative documentation

When you generate documentation, DocBlox actually creates a SQLite database in which to store the information it learns while parsing your code base. This allows it to be very, very fast both when parsing (it can free information from memory once it's done analyzing a class or file) as well as when transforming into output (as it can iteratively query the database for structures).
What does this mean for you?
Well, first, if you want to try out new templates, it won't need to re-parse your source code -- it simply generates the new output from the already parsed definitions. This can be very useful particularly when creating new templates. Generation is oftentimes instantaneous for small projects.
Second, it means that you can build the full documentation once, and only periodically update it (which you can do using the --force option). This is particularly useful for build processes.

Configuration

One problem with any rich CLI tool is that you often get a proliferation of options, and remembering them between invocations can be hard (particularly if you only run the tool during releases). DocBlox allows you to create a configuration file, docblox.xml, in your project. The format is relatively simple; the (mostly) equivalent to the above options I've used is as below:

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>                                     
<docblox>
    <parser>
        <target>documentation/api</target>
    </parser>
    <transformer>
        <target>documentation/api</target>
    </transformer>
    <files>
        <directory>path/to/source</directory>
    </files>
    <transformations>
        <template>
            <name>zend</name>
        </template>
    </transformations>
</docblox>
You can't specify the title in the configuration, but often that will be template-driven, anyways.
DocBlox will then look for this file in the current directory and simply use it, allowing you to invoke it as follows:

prompt> docblox run
Or you can specify the configuration file yourself:

prompt> docblos run -c config.xml
(Side note: on the release current as of when I write, 0.12.2, I have not successfully been able to specify the template name.)

Search

If you look carefully at the generated output, you'll notice a search box. By default, this doesn't work... because it points to a PHP script! When installed on a server capable of serving PHP, however, it can be used to help find classes, methods, and more. As an example, you can search the Zend Framework 1.11 API documentation.

Conclusions

Hopefully this tutorial will get you started investigating DocBlox. I've been quite happy with what I've seen so far of the project, and gladly recommend it. There are other alternatives, however, and I also suggest you try those out; Liip recently published a comparison of features, and that article can be used as a starting point for your own investigations.
(Disclosure : Mike van Riel, he's developed DocBlox).

Saturday, 31 August 2013

Enable and Install cURL in Apache -Ubuntu

apache

This extension for PHP allows for behind the scenes communication between php pages.  This can come in handy if you are needing to communicate or send information between clients and servers.  Following are the steps need to install and test the extension on an Ubuntu Apache web server.

Install Components


sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

Restart the Server


sudo service apache2 restart

Create a test page on the computer to ensure that everything is working.
test.php
<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>
browse to the page and make sure there are no errors

Wednesday, 21 August 2013

php tomezone related troubleshooting

Warning: socket_bind() [function.socket-bind]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Asia/Calcutta' for 'IST/5.0/no DST' instead in /var/www/chat_php.php on line 19



solution:-

try this
 

date_default_timezone_set('Asia/Calcutta');
 




At beginning your php file.

Friday, 16 August 2013

Laravel Quickstart (PHP framework)

Installation#

To install the Laravel framework, you may issue the following command from your terminal:
composer create-project laravel/laravel your-project-name --prefer-dist
Or, you may also download a copy of the repository from Github. Next, after installing Composer, run the composer install command in the root of your project directory. This command will download and install the framework's dependencies.
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.

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 you