Laravel 4 example application

Laravel Framework is a framework of php language getting more and more popularity. It can be installed in several ways. One of them is to download the framework skeleton from the github repository. Then, using Composer we install components of the framework: after downloading packages from the repository run the text console and move to the folder where you installed Laravel and type the command ‘php composer.phar install’ (composer.phar file put in a directory with PHP framework ) or in Windows ‘composer install’. In the browser navigate to the ‘public’ folder. If you see the page as shown below, it means that the installation was correctly. If not, set recursive write permissions for the app/storage folder.

We are going to build example application – to do list. Application will display all created tasks, will be able to add a new task, preview individual tasks, edit and delete existing ones. In addition, you will be able to change the status of an existing task on realized or unrealized.

1. User requests support.

2. Creating a table in the database.

3. Creating controller.

4. Preparing main template.

5. Application views.

User requests support


The main part of our application is in the app/routes.php file. We enter here all possible user queries. In our case, the file will look like this:

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/','SampleController@index'); 
Route::get('create','SampleController@create'); 
Route::post('store','SampleController@store'); 
Route::get('destroy/{id}','SampleController@destroy'); 
Route::get('show/{id}','SampleController@show'); 
Route::get('edit/{id}','SampleController@edit'); 
Route::post('update/{id}','SampleController@update'); 
Route::get('change-status/{id}','SampleController@changeStatus');

Remove old content and save the above code. . We’ve got eight static method calls of Route class. Each method is called depending on the user action. Methods are called as types of user requests (in this case, get and post). The first parameter of each method specifies the link the user clicked. For example, ‘/’ means loading the home page, ‘create’ means to click www.example.pl/create, ‘update/{id}’ is a call to www.example.pl/update/x, where x is the first parameter of the controller. In this case, the method is ‘update’ as seen in the second routing parameter . This parameter is binomial. Separator is the @ sign, the first part is the name of the controller class and the second is the name of the method to call. Meanings of created routes:

  • Create – loading the form to save the new task
  • Store – saving new task
  • Destroy – deleting task
  • Show – loading page with details of a specific task
  • Edit – editing task
  • Update – saving changes to the existing task
  • Change status – changing status

In short Route::get('change-status/{id}','SampleController@changeStatus'); means: if the user clicked on ‘change-status/id’, then changestatus() is called from SampleController with id parameter.

Creating a table in the database for application


Sql command creating the table for the sample application:

CREATE TABLE `to-do` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`content` text NOT NULL,
`status` enum('Y','N') DEFAULT 'N',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8

Create a table and save the access data to the MySQL database in the app/config/database.php file.

Become a Professionalist in Web Application Development! Enroll In The Course Of Laravel You will also learn how to create hybrid applications for smartphones

Creating controller


In this simple example application we do not need model file, we will write down everything in the controller. We would create a model when we wanted to use the mode of communication with the database called “eloquent orm” that simplifies the use of the database. About that may be in the next episode. Here we will use standard SQL queries.

<?php

class SampleController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index() {
        $tasks = DB::select('select * from `to-do`'); // we get all the tasks from the table

        return View::make('home')->with('tasks', $tasks); // we create a view with the data about all jobs
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create() {
        return View::make('task.create-task');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store() {

        $validator = Validator::make(
                        [
                    'task-name' => Input::get('task-name'),
                    'task-content' => Input::get('task-content')
                        ], [
                    'task-name' => 'required',
                    'task-content' => 'required'
                        ]
        );

        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        }


        DB::insert('insert into `to-do` values (null,?,?,default)', [ Input::get('task-name'), Input::get('task-content')]);

        return Redirect::to('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id) {
        $task = DB::select('select * from `to-do` where id=? limit 1', [$id]); // sql prepared statement
        $task = $task[0];
        return View::make('task.show-task')->with('task', $task);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id) {
        $task = DB::select('select * from `to-do` where id=?', [$id]);
        $task = $task[0];
        return View::make('task.edit-task')->with('task', $task);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        $validator = Validator::make(
                        [
                    'task-name' => Input::get('task-name'),
                    'task-content' => Input::get('task-content')
                        ], [
                    'task-name' => 'required',
                    'task-content' => 'required'
                        ]
        );

        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        }

        DB::update('update `to-do` set name = ?,content = ? where id=?', [Input::get('task-name'), Input::get('task-content'), $id]);

        return Redirect::to('/');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        DB::delete('delete from `to-do` where id=?', [$id]);
        return Redirect::to('/');
    }

    public function changeStatus($id) {
        $query = "update `to-do` set status = case when status = 'Y' then 'N' else 'Y' end where id=?";
        DB::update($query, [$id]);
        return Redirect::to('/');
    }

//end class
}

Write the above code in the app/controllers/SampleController.php file. We’ve got here eight public methods – exactly as defined in the routing file. Each has a specific role specified in first chapter. Look at the comments in the code but here we will describe the update method: we create validator object. The method that creates the validator object accepts two arguments – two array, the first contains the names and values of validated fields, the second – the validation rules for the given names. Input::get('task-name') corresponds to the construction of $_POST['task-name']. In the second array the ‘required’ keyword means that the field is required. Then on the object we created we call fails() method, which checks whether the validation rules passed. In this case, it checks whether the form fields named task-name and task-content are not empty. If there are unfilled fields then we have to reload the form. To this end, we call several methods of Redirect class. withIput() method will cause our form remember the values entered previously by the user. withErrors() method will produce in our view $errors variable by which we’ll show validation errors. When there are no validation errors database table will be updated. For this purpose it is used here Prepared statements mechanism, so you do not have to filter the variables, we automatically receive protection against ‘SQL injection’ attack as variables to the SQL query are substituted at the time of execution and not before, so no one can change the original SQL queries. At the end we redirect to the main page.

Preparing main template for the individual views of our application


We’ll start with the main template file that is the starting point for all views. Here’s a sample template:

<!DOCTYPE html>
<html lang="pl">
    <head>
        <meta charset="utf-8">
        <!--[if IE]>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <![endif]-->
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Basic Template</title>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&subset=latin-ext' rel='stylesheet' type='text/css'>
        <style>
            body,html {
                font-family: 'Lora', serif;
                font-size: 20px;
                font-weight: 400;
                line-height: 1.5em;
            }
            .error {
                color: red;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <a href="{{URL::to('/')}}" class="pull-right">home</a>
            @yield('content')
        </div>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
        <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
    </body>
</html>

Notice the structure @yield('content'). This is part of Laravel template engine. In this place will be inserted the dynamic content of our application. Details in next chapters. Pay attention also to the line above. A pair of double curly brackets {{…}} is the basic element of the Laravel template engine. It replaces the construction of <?php echo….;?>. Create app/views/layouts folder and write the above code in template.blade.php file. The presence of the ‘blade’ keyword in the file name indicates Laravel that you are using his template system. If you do not have this keyword you need to use standard php tags. However, you can use php tags next to the Laravel template directives.

Application views


Home page will display a list of tasks. Write it in app/views/home.blade.php file.

@extends('layouts.template')

@section('content')

<h1>Task list <small><button type="button" class="btn btn-primary btn-sm" onclick="location.href = 'create'">Add task</button></small></h1>
<br />
<table class="table table-bordered table-hover">
    <tr>
        <th>Task name</th>
        <th>Edit</th>
        <th>Delete</th>
        <th>Status</th>
    </tr>

    @foreach($tasks as $task)
    <tr>
        <td><a href="{{ URL::to('show') }}/{{ $task->id }}">{{{ $task->name }}} </a></td>
        <td><a href="edit/{{ $task->id }}">edit</a></td>
        <td><a href="destroy/{{ $task->id }}" onclick="return confirm('Na pewno?');">delete</a></td>
        <?php
        if ($task->status == 'Y')
            $status = 'X';
        else
            $status = ' ';
        ?>
        <td><a href="change-status/{{$task->id}}">[ {{$status}} ]</a></td>
    </tr>
    @endforeach

</table>

@stop

@extends('layouts.template') means that our template is a previously created template.blade.php file. Note advantage – you can create a separate template for specific sub-page (for example other footer on a specific sub-page). The dot between words layouts and template is a replacement for a slash / . So, in other words, it is about the template.blade.php file located in the layouts folder. Remember @yield('content') in template file? In this place will be pasted what in home.blade.php file is located between @section ('content') and @stop. Here we have a foreach loop in which we operate on the $tasks object created in the controller.

It’s time to create individual views of our application. We’ll start with the view that displays the form to add a new task. Write the above code into app/views/task/create-task.blade.php file.

@extends('layouts.template')

@section('content')

<h1>Add new task</h1>
<br />

<form role="form" method="post" action="store">

    <div class="row">
        <div class="form-group col-xs-6">
            <label>Task name</label> <span class="error">{{ $errors->first('task-name') }}</span>
            <input type="text" name="task-name" class="form-control">
        </div>
    </div>

    <div class="row">
        <div class="form-group col-xs-6">
            <label>Task content</label><span class="error">{{ $errors->first('task-content') }}</span>
            <textarea name="task-content" class="form-control" rows="6"></textarea>
        </div>
    </div>

    <button type="submit" class="btn btn-default">Save task</button>
</form>

@stop

{{ $errors->first('task-name') }} is responsible for displaying error if validation went wrong.
Time for a view displaying a single task:

@extends('layouts.template')

@section('content')

<h1>{{{ $task->name }}}</h1>
<p> {{{ $task->content }}}</p>

@stop

Write the above code as app/views/task/show-task.blade.php.
Please note that this time to the construction of {{{ $task->content }}} we added three braces on each side and not two as usual. This means that the data displayed in this place will be filtered in case someone wrote malicious javascript code, which protects us against a potential XSS attack.
And at the end we have view to edit the task, which is almost identical to creating a task one. But this time we write it as a separate file:

@extends('layouts.template')

@section('content')

<h1>Edit task</h1>
<br />

<form role="form" method="post" action="{{ URL::to('update/'.$task->id) }} ">

    <div class="row">
        <div class="form-group col-xs-6">
            <label>Task name</label><span class="error">{{ $errors->first('task-name') }}</span>
            <input type="text" name="task-name" class="form-control" value="{{{ $task->name }}}">
        </div>
    </div>

    <div class="row">
        <div class="form-group col-xs-6">
            <label>Task content</label><span class="error">{{ $errors->first('task-content') }}</span>
            <textarea name="task-content" class="form-control" rows="6">{{{ $task->content }}}</textarea>
        </div>
    </div>

    <button type="submit" class="btn btn-default">Save task</button>
</form>

@stop

Write the above code as app/views/task/edit-task.blade.php.
Our application – a list of tasks is complete.

 

enroll in the course of Laravel framework >>>> or affiliate program
Share

Leave a Reply

Your email address will not be published. Required fields are marked *