Home » 2016 » April

Monthly Archives: April 2016

Mastering Laravel

Mastering Laravel

Mastering Laravel by Christopher John Pecoraro

PHP, a free and open source programming language, is continuing renaissance and Laravel is at the forefront. Laravel 5 is proving to be the most usable framework for novice and expert programmers alike. Following modern PHP’s object-oriented best practices, reduce the time to market and build robust web and API-driven mobile applications that can be automatically tested and deployed.
You will learn how to rapidly develop software applications using the Laravel 5 PHP framework.
What this book covers
Chapter 1, Designing Done Right with phpspec, speaks about how to configure Laravel 5 for phpspec to perform modern unit testing, to use phpspec to design classes, and to perform unit and functional testing.
Chapter 2, Automating Tests – Migrating and Seeding Your Database, covers database migrations, the mechanics behind them and how to create a seed for testing.
Chapter 3, Building Services, Commands, and Events, talks about Model-View-Controller
and how has evolved into services, commands, and events to decouple code and practice separation of concerns.
Chapter 4, Creating RESTful APIs, takes you through the creation of a RESTful API: the basic CRUD operations (create, read, update, and delete), as well as discussing some best practices and hypermedia controls (HATEOAS).
Chapter 5, Using the Form Builder, takes you to the web interface side of things and shows you how to take advantage of the some of the newest features of Laravel 5 to create web forms. Reversed routing will be discussed here as well.
Chapter 6, Taming Complexity with Annotations, focuses on annotations. The routes. php file easily becomes messy when an application grows in complexity. Using annotations inside of controllers, code legibility is drastically increased; however, there are some disadvantages in addition to the advantages.
Chapter 7, Filtering Requests with Middleware, shows you how to create reusable filters that can be called either before or after the controllers.
Chapter 8, Querying the Database with the Eloquent ORM, helps you learn how to use an ORM in a way to reduce the probability of errors in coding, increase the security and reduction of SQL-injection probability, and also learn how to deal with the limits of the Eloquent ORM.
Chapter 9, Scaling Laravel, speaks about scaling an application to move it into a cloudbased architecture. The read/write master/slave configuration is discussed and the reader is guided through the configuration.
Chapter 10, Building, Compiling, and Testing with Elixir, introduces Elixir. Elixir is based on gulp, which is a task runner and is a series of build scripts that automates common tasks in the Laravel software development workflow.
What you need for this book
We’ll need the following software:
• Apache/Nginx
• PHP 5.4 or greater
• MySQL or similar
• Composer
• phpspec
• Node.js
• npm
Who this book is for
If you are an experienced novice or a capable PHP programmer who has a basic understanding of the concepts of modern PHP (at least version 5.4), then this book is ideal for you.

Create a CRUD Application with Laravel 5.2 (Part-6)

Editing user information

Now as we learned how easy it is to add and list users. Let’s jump into editing a user. In our list users view we have the edit link with the following code:

{{ link_to_route('users.edit', 'Edit', array($user->id), array('class' => 'btn btn-info')) }}

Here, the link_to_route function will generate a link /users/<id>/edit, which will call the resourceful Controller user, and Controller will bind it with the edit method.

So here is the code for editing a user. First of all we are handling the edit request by adding the following code to our UsersController:

    public function edit($id)
    {
        $user = User::find($id);
        if (is_null($user))
        {
            return Redirect::route('users.index');
        }
        return View::make('users.edit', compact('user'));
    }

So when the edit request is fired, it will hit the edit method described in the preceding code snippet. We would need to find whether the user exists in the database. So we use our user model to query the ID using the following line of code:

$user = User::find($id);

Eloquent object’s find method will query the database just like a normal SQL.

Select * from users where id = $id

Then we will check whether the object we received is empty or not. If it is empty, we would just redirect the user to our list user’s interface. If it is not empty, we would direct the user to the user’s edit view with our Eloquent object as a compact array.

So let’s create our edit user view at app/resouces/users/edit.blade.php, as follows:

@extends('users.scaffold')

@section('main')

<h1>Edit User</h1>
{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.update', $user->id))) }}
    <ul>
        <li>
            {{ Form::label('username', 'Username:') }}
            {{ Form::text('username') }}
        </li>
        <li>
            {{ Form::label('password', 'Password:') }}
            {{ Form::text('password') }}
        </li>
        <li>
            {{ Form::label('email', 'Email:') }}
            {{ Form::text('email') }}
        </li>
        <li>
            {{ Form::label('phone', 'Phone:') }}
            {{ Form::text('phone') }}
        </li>
        <li>
            {{ Form::label('name', 'Name:') }}
            {{ Form::text('name') }}
        </li>
        <li>
            {{ Form::submit('Update', array('class' => 'btn btn-info')) }}
            {{ link_to_route('users.show', 'Cancel', $user->id, array('class' => 'btn')) }}
        </li>
    </ul>
{{ Form::close() }}

@if ($errors->any())
    <ul>
        {{ implode('', $errors->all('<li class="error">:message</li>')) }}
    </ul>
@endif

@stop

Here we are extending our users’ layout as always and defining the main section. Now in the main section, we are using the Form helper to generate a proper REST request for our controller.

{{ Form::model($user, array('method' => 'PATCH', 'route' => array('users.update', $user->id))) }}

Now, you may have not dealt with the method PATCH as we only know of two protocols, GET and POST, as most browsers generally support only these two methods. The REST method for editing is PATCH, and what Laravel does is that it creates a hidden token so it knows which method to call. So the preceding code generates the following code:

<form method="POST" action="http://ch3.sr/users/1" accept-charset="UTF-8">
<input name="_method" type="hidden" value="PATCH">

It actually fires a POST method for browsers that are not capable for handling the PATCH method. Now, when a user submits this form, it will send a request to the update method of UsersController via the resourceful Controller we set in routes.php.

Here is the update method of UsersController:

public function update($id)
    {
        $input = Input::all();
        $validation = Validator::make($input, User::$rules);
        if ($validation->passes())
        {
            $user = User::find($id);
            $user->update($input);
            return Redirect::route('users.show', $id);
        }
return Redirect::route('users.edit', $id)
            ->withInput()
            ->withErrors($validation)
            ->with('message', 'There were validation errors.');
    }

Here Laravel will pass the ID of the user we are editing in the update method. We can use this ID to find the user via our user model’s Eloquent object’s find method. Then we will update the Eloquent object with an input array just like we did in the insert operation.

Deleting user information

To delete a user we can use the destroy method. If you go to our user lists view, you can find the following delete link’s generation code:

{{ Form::open(array('method' => 'DELETE', 'route' => array('users.destroy', $user->id))) }}
{{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
{{ Form::close() }}

The preceding code is handled by Laravel similar to the way in which it handles the PATCH method. Laravel will generate a post request with the hidden method token set as PATCH, which it can recognize when it hits the Laravel request object.

At UsersController this request will hit the destroy() method as follows:

    public function destroy($id)
    {
        User::find($id)->delete();
        return Redirect::route('users.index');
    }

Laravel will directly send id to the destroy method, so all we have to do is use our user model and delete the record with its delete method. If you noticed Eloquent allows us to chain methods. Isn’t it sweet? So there would be no queries but just one line to delete a user.

That’s one of the reasons to use Eloquent objects in your projects. It allows you to quickly interact with the database and you can use objects to match your business logic.

Adding pagination to our list users

One of the painful tasks most developers face often is that of pagination. With Laravel it’s no more the case, as Laravel provides a simple approach to set pagination to your pages.

Let’s try to implement pagination to our list user’s method. To set pagination we can use the paginate method with Laravel’s Eloquent object. Here is how we can do that:

public function index()
{
  $users = User::paginate(5);
  return View::make('users.index', compact('users'));
}

The preceding code is the index method of the UsersController class, which we were using previously for getting all the users with User::all(). We just used the paginate method to find five records from the database. Now in our list users view, we can use the following code to display pagination links:

{{ echo $users->links(); }}
Here the links() method will generate pagination links for you. And best part, Laravel will manage the code for pagination. So all you have to do is use paginate method with your eloquent object and links method to display generated links.

 

Wrapping up

So we have set up our simple CRUD application and now we know how easy it is with Laravel to set up CRUD operations. We have seen Eloquent Laravel’s database ORM that makes working with a database simple and easy. We have learned how to list users, create new users, edit users, delete users, and how to add pagination to our application.

The End. https://www.dunebook.com/

Create a CRUD Application with Laravel 5.2 (Part-5)

Creating new users

Now as we have listed our users, let’s write the code for creating new users. To create a new user, we will need to create the Controller method and bind the view for displaying the new user form. We would need to create the Controller method for saving the user too. Now as we have bound the resourceful Controller, we don’t need to create separate routes for each of our request. Laravel will handle that part if we use REST methods.

So first let’s edit the controller at /app/http/controllers/UsersController.php to add a method for displaying the view:

    public function create()
    {
        return View::make('users.create');
    }

This will call a view at /app/resources/users/create.blade.php. So let’s define our create.blade.php view as follows:

@extends('layouts.users')

@section('main')

<h1>Create User</h1>

{{ Form::open(array('route' => 'users.store')) }}
    <ul>

        <li>
            {{ Form::label('name', 'Name:') }}
            {{ Form::text('name') }}
        </li>

        <li>
            {{ Form::label('username', 'Username:') }}
            {{ Form::text('username') }}
        </li>

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

        <li>
            {{ Form::label('password', 'Confirm Password:') }}
            {{ Form::password('password_confirmation') }}
        </li>        

        <li>
            {{ Form::label('email', 'Email:') }}
            {{ Form::text('email') }}
        </li>

        <li>
            {{ Form::label('phone', 'Phone:') }}
            {{ Form::text('phone') }}
        </li>


        <li>
            {{ Form::submit('Submit', array('class' => 'btn')) }}
        </li>
    </ul>
{{ Form::close() }}

@if ($errors->any())
    <ul>
        {{ implode('', $errors->all('<li class="error">:message</li>')) }}
    </ul>
@endif

@stop

Let’s try to understand our preceding view. Here we are extending the users layout we created in our List Users section. Now in the main section, we are using Laravel’s Form helper to generate our form. This helper generates HTML code via its methods such as label, text, and submit.

Refer to the following code:

{{ Form::open(array('route' => 'users.store')) }}

The preceding code will generate the following HTML code:

<form method="POST" action="http://localhost/users" accept-charset="UTF-8">

As you can see it’s really convenient for us to not worry about linking things correctly. Now let’s create our store method to store our form data into our users table:

public function store()
    {
        $input = Input::all();
        $validation = Validator::make($input, User::$rules);

        if ($validation->passes())
        {
            User::create($input);

            return Redirect::route('users.index');
        }

        return Redirect::route('users.create')
            ->withInput()
            ->withErrors($validation)
            ->with('message', 'There were validation errors.');
    }

Here we are first validating all the input that came from the user. The Input::all () function fetches all the $_GET and $_POST variables and puts it into a single array. The reason why we are creating the single input array is so we can check that array against validation rules’ array. Laravel provides a very simple Validation class that can be used to check validations. We could use it to check whether validations provided in the rules array are followed by the input array by using the following line of code:

$validation = Validator::make ($input, User::$rules);

Rules can be defined in an array with validation attributes separated by the column “|”. Here we are using User::$rules where User is our Model and it will have following code:

class User extends Eloquent {

  protected $guarded = array('id');
  protected $fillable = array('name', 'email');

  public static $rules = array(
    'name' => 'required|min:5',
    'email' => 'required|email'
  );
}

As you can observe we have defined two rules mainly for name and e-mail input fields. If you are wondering about $guarded and $fillable variables, these variables are used to prevent mass assignment. When you pass an array into your Model’s create and update methods, Laravel tries to match the right columns and sets values in the database. Now for instance, if a malicious user sends a hidden input named id and changes his ID via the update method of your form, it could be a huge security hole; to prevent this, we should define the $guarded and $fillable arrays. The $guarded array will guard the columns defined in the guarded array, that is, it will prevent anyone from changing values in that column. The $fillable array will only allow elements defined in $fillable to be updated.

Now we can use the $validation instance we created to check for validations.

$result = $validation->passes();
echo $result; // True or false

If you see our code now, we are checking for validation via the passes() method in our Store() method of UserController. Now if validation gets passed, we can use our user Model to store data into our database. All you need to do is call the Create method of the Model class with the $input array. So refer to the following code:

User::create($input);

The preceding code will store our $input array into the database; yes, it’s equivalent to your SQL query.

Insert into user(name,password,email,city) values (x,x,..,x);

Here we have to fill either the $fillable or $guarded array in the model, otherwise, Laravel will throw a mass assignment exception. Laravel’s Eloquent object automatically matches our input array with the database and creates a query based on our input array. Don’t you think this is a simple way to store input into the database? If user data is inserted, we are using Laravel’s redirect method to redirect it to our list of users’ pages. If validation fails, we are sending all of the input with errors from the validation object into our create users form.

Source: https://www.dunebook.com

 

Create a CRUD Application with Laravel 5.2 (Part-4)

Now let’s look at the View part. Before that, we need to know about Blade. Blade is a templating engine provided by Laravel. Blade has a very simple syntax, and you can determine most of the Blade expressions within your view files as they begin with @. To print anything with Blade, you can use the {{ $var }} syntax. Its PHP-equivalent syntax would be:

<?php echo $var; ?>

Now back to our view; first of all, we need to create a view file at /resources/views/users/index.blade.php, as our statement would return the view file from users.index. We are passing a compact users array to this view. So here is our index.blade.php file:

@section('main')

<h1>All Users</h1>

<p>{{ link_to_route('users.create', 'Add new user') }}</p>

@if ($users->count())
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>Username</th>
        <th>Password</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Name</th>
            </tr>
        </thead>

        <tbody>
            @foreach ($users as $user)
                <tr>
                    <td>{{ $user->username }}</td>
          <td>{{ $user->password }}</td>
          <td>{{ $user->email }}</td>
          <td>{{ $user->phone }}</td>
          <td>{{ $user->name }}</td>
                    <td>{{ link_to_route('users.edit', 'Edit', array($user->id), array('class' => 'btn btn-info')) }}</td>
                    <td>
          {{ Form::open(array('method' 
=> 'DELETE', 'route' => array('users.destroy', $user->id))) }}                       
                            {{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
                        {{ Form::close() }}
                    </td>
                </tr>
            @endforeach
              
        </tbody>
      
    </table>
@else
    There are no users
@endif

@stop

Let’s see the code line by line. In the first line we are extending the user layouts via the Blade template syntax @extends. What actually happens here is that Laravel will load the layout file at /app/views/layouts/user.blade.php first.

Here is our user.blade.php file’s code:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
        <style>
            table form { margin-bottom: 0; }
            form ul { margin-left: 0; list-style: none; }
            .error { color: red; font-style: italic; }
            body { padding-top: 20px; }
        </style>
    </head>

    <body>

        <div class="container">
            @if (Session::has('message'))
                <div class="flash alert">
                    <p>{{ Session::get('message') }}</p>
                </div>
            @endif

            @yield('main')
        </div>

    </body>

</html>

Now in this file we are loading the Twitter bootstrap framework for styling our page, and via yield('main') we can load the main section from the view that is loaded. So here when we load http://localhost/laravel/public/users, Laravel will first load the users.blade.php layout view and then the main section will be loaded from index.blade.php.

Now when we get back to our index.blade.php, we have the main section defined as @section('main'), which will be used by Laravel to load it into our layout file. This section will be merged into the layout file where we have put the @yield ('main') section.

We are using Laravel’s link_to_route method to link to our route, that is, /users/create. This helper will generate an HTML link with the correct URL. In the next step, we are looping through all the user records and displaying it simply in a tabular format. Now if you have followed everything, you will be greeted by the following screen:

Crud-User

Create a CRUD Application with Laravel 5.2 (Part-3)

As you can see, resource Controller really makes your work easy. You don’t have to create lots of routes. Also Laravel ‘s artisan-command-line generator can generate resourceful Controllers, so you will write very less boilerplate code. And you can also use the following command to view the list of all the routes in your project from the root of your project, launching command line:

$ php artisan routes

Now let’s get back to our basic task, that is, reading users. Well now we know that we have UserController.php at /app/controller with the index method, which will be executed when somebody launches http://localhost/laravel/public/users. So let’s edit the Controller file to fetch data from the database.

Well as you might remember, we will need a Model to do that. But how do we define one and what’s the use of Models? You might be wondering, can’t we just run the queries? Well Laravel does support queries through the DB class, but Laravel also has Eloquent that gives us our table as a database object, and what’s great about object is that we can play around with its methods. So let’s create a Model.

If you check your path /app/User.php, you will already have a user Model defined. It’s there because Laravel provides us with some basic user authentication. Generally you can create your Model using the following code:

class User extends Eloquent {}

Now in your controller you can fetch the user object using the following code:

$users = User::all();
$users->toarray();

Yeah! It’s that simple. No database connection! No queries! Isn’t it magic? It’s the simplicity of Eloquent objects that many people like in Laravel.

But you have the following questions, right?

  • How does Model know which table to fetch?
  • How does Controller know what is a user?
  • How does the fetching of user records work? We don’t have all the methods in the User class, so how did it work?

Well models in Laravel use a lowercase, plural name of the class as the table name unless another name is explicitly specified. So in our case, User was converted to a lowercase user and used as a table to bind with the User class.

Models are automatically loaded by Laravel, so you don’t have to include the reference of the Model file. Each Model inherits an Eloquent instance that resolves methods defined in the model.php file at vendor/Laravel/framework/src/Illumininate/Database/Eloquent/ like all, insert, update, delete and our user class inherit those methods and as a result of this, we can fetch records via User::all().

So now let’s try to fetch users from our database via the Eloquent object. I am updating the index method in our app/controllers/UsersController.php as it’s the method responsible as per the REST convention we are using via resource Controller.

public function index()
  {

        $users = User::all();

return View::make(‘users.index’, compact(‘users’));
}

 

Create a CRUD Application with Laravel 5.2 (Part-2)

Listing the users – read users from database

Let’s read users from the database. We would need to follow the steps described to read users from database:

  • A route that will lead to our page
  • A controller that will handle our method
  • The Eloquent Model that will connect to the database
  • A view that will display our records in the template

So let’s create our route at /app/http/routes.php. Add the following line to the routes.php file:

Route::resource('users', 'UserController');

If you have noticed previously, we had Route::get for displaying our page Controller. But now we are using resource. So what’s the difference?

In general we face two types of requests during web projects: GET and POST. We generally use these HTTP request types to manipulate our pages, that is, you will check whether the page has any POST variables set; if not, you will display the user form to enter data. As a user submits the form, it will send a POST request as we generally define the <form method="post"> tag in our pages. Now based on page’s request type, we set the code to perform actions such as inserting user data into our database or filtering records.

What Laravel provides us is that we can simply tap into either a GET or POST request via routes and send it to the appropriate method. Here is an example for that:

Route::get('/register', 'UserController@showUserRegistration');
Route::post('/register', 'UserController@saveUser');

See the difference here is we are registering the same URL, /register, but we are defining its GET method so Laravel can call UserController class’ showUserRegistration method. If it’s the POST method, Laravel should call the saveUser method of the UserController class.

You might be wondering what’s the benefit of it? Well six months later if you want to know how something’s happening in your app, you can just check out the routes.php file and guess which Controller and which method of Controller handles the part you are interested in, developing it further or solving some bug. Even some other developer who is not used to your project will be able to understand how things work and can easily help move your project. This is because he would be able to somewhat understand the structure of your application by checking routes.php.

Now imagine the routes you will need for editing, deleting, or displaying a user. Resource Controller will save you from this trouble. A single line of route will map multiple restful actions with our resource Controller. It will automatically map the following actions with HTTP verbs:

HTTP VERB ACTION
GET READ
POST CREATE
PUT UPDATE
DELETE DELETE

On top of that you can actually generate your Controller via a simple command-line artisan using the following command:

$ php artisan make:controller usercontroller

This will generate UsersController.php with all the RESTful empty methods, so you will have an empty structure to play with. Here is what we will have after the preceding command:

class UserController extends BaseController {

  /**
   * Display a listing of the resource.
   *
   * @return Response
   */
  public function index()
  {
    //
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return Response
   */
  public function create()
  {
    //
  }

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

  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return Response
   */
  public function show($id)
  {
    //
  }

  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return Response
   */
  public function edit($id)
  {
    //
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function update($id)
  {
    //
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return Response
   */
  public function destroy($id)
  {
    //
  }
  
}

Now let’s try to understand what our single line route declaration created relationship with our generated Controller.
HTTP VERB Path Controller Action/method
GET /Users Index
GET /Users/create Create
POST /Users Store
GET /Users/{id} Show (individual record)
GET /Users/{id}/edit Edit
PUT /Users/{id} Update
DELETE /Users/{id} Destroy

Source: https://www.dunebook.com

Create a CRUD Application with Laravel 5.2 (Part-1)

let’s create a simple CRUD application with Laravel . we have updated This tutorial to laravel 5.2 . The application we want to create will manage the users of our application. We will create the following list of features for our application:

  • List users (read users from the database)
  • Create new users
  • Edit user information
  • Delete user information
  • Adding pagination to the list of users

Now to start off with things, we would need to set up a database. So if you have phpMyAdmin installed with your local web server setup, head over to http://localhost/phpmyadmin; if you don’t have phpMyAdmin installed, use the MySQL admin tool workbench to connect with your database and create a new database.

Requirements -> html form –> please install this and follow instructions from official site
Now we need to configure Laravel to connect with our database. So head over to your Laravel application folder, open config/database.php, change the MySQL array, and match your current database settings. Here is the MySQL database array from database.php file:

‘mysql’ => array(
‘driver’ => ‘mysql’,
‘host’ => ‘localhost’,
‘database’ => ”,
‘username’ => ‘root’,
‘password’ => ”,
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,
),

Now we are ready to work with the database in our application. Let’s first create the database table Users via the following SQL queries from phpMyAdmin or any MySQL database admin tool;

CREATE TABLE IF NOT EXISTS ‘users’ (
‘id’ int(10) unsigned NOT NULL AUTO_INCREMENT,
‘username’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘password’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
’email’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘phone’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘name’ varchar(255) COLLATE utf8_unicode_ci NOT NULL,
‘created_at’ timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00’,
‘updated_at’ timestamp NOT NULL DEFAULT ‘0000-00-00 00:00:00’,
PRIMARY KEY (‘id’)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

Now let’s seed some data into the Users table so when we fetch the users we won’t get empty results. Run the following queries into your database admin tool:

INSERT INTO ‘users’ (‘id’, ‘username’, ‘password’, ’email’, ‘phone’, ‘name’, ‘created_at’, ‘updated_at’) VALUES
(1, ‘john’, ‘johndoe’, ‘johndoe@gmail.com’, ‘123456’, ‘John’, ‘2013-06-07 08:13:28’, ‘2013-06-07 08:13:28’),
(2, ‘amy’, ‘amy.deg’, ‘amy@outlook.com’, ‘1234567’, ‘amy’, ‘2013-06-07 08:14:49’, ‘2013-06-07 08:14:49’);

Note

Later we will see how we can manage our database via Laravel 4’s powerful migrations features. At the end of this chapter, I will introduce you to why it’s not a good practice to manually create SQL queries and make changes to the database structure. And I know that passwords should not be plain too!

Source : https://www.dunebook.com

Learning Laravel’s Eloquent

Learning Laravel's Eloquent

Develop amazing data-based applications with Eloquent, the Laravel framework ORM

If you are associated with the field of web development, you know how important data is. The web runs on data, so it’s essential for developers to think of quick and effective ways to deal with it. Eloquent is an awesome ORM that comes with the Laravel PHP framework. It is unique and is very beneficial to developers as it allows them to define models, relationships, and many complex operations with a really easy and intuitive syntax, without sacrificing performance. Performing an interesting number of operations on multiple tables without writing long queries with objects will be a bed of roses.

This book will take you through developing brilliant data-based applications with Eloquent, the Laravel framework ORM.
You will do the following:
• Build highly efficient applications with the Eloquent ORM using an
expressive syntax
• Get to grips with the power of relationships and how Eloquent handles them
• Go beyond simple theory with various step-by-step code examples

So, let’s get started!

What this book covers
Chapter 1, Setting Up Our First Project, will discuss how to deal with Composer and Homestead. We will also cover the installation process of our very first Laravel project.
Chapter 2, Building the Database with the Schema Builder Class, will discuss the Schema Builder Class. We will analyze everything you can do with the class, look at different types of indexing, and learn about the methods that the Schema class provides.

; “> Chapter 3, The Most Important Element – the Model!, will help us implement some
“create,” “read,” “update,” and “delete” logic for our items. We will also explore
some useful methods and features of the model class.
Chapter 4, Exploring the World of Relationships, will help us discover how to work with different types of relationships and how to query and use them in a comfortable and clean way. Also, we will learn how to insert and delete related models in our database, or update existing ones.
Chapter 5, Using Collections to Enhance Results, will talk about collections. We will work with some results transformation methods and with the elements that make up a collection.
Chapter 6, Everything under Control with Events and Observers, will allow us to learn everything about the events in the context of Eloquent models. Right after, we will cover model events and model observers.
Chapter 7, Eloquent… without Laravel!, will explore the structure of the database package and see what is inside it. After that, we will learn how to install the “illuminate/database” package separately for your project and how to configure it for its first use. Yes, exactly: Eloquent without Laravel!
Chapter 8, It’s Not Enough! Extending Eloquent, Advanced Concepts, will explore two different ways to extend Eloquent, and move on to learn about the Repository pattern.

Laravel 5 Essentials

Laravel 5 Essentials

Explore the fundamentals of Laravel, one of the most expressive and robust PHP frameworks available

Application frameworks have grown in popularity over the past five years. There has been a tremendous shift from handwriting all code to leveraging these powerful frameworks with prebuilt components and features. However, with anything that comes to be in fashion, there are now a lot of contending options, and each of them viable.
While CodeIgniter was one of the first frameworks to enjoy widespread popularity, this popularity would come to be its undoing years later, as its large spread use and low barrier to entry meant it couldn’t take advantage of newer versions of PHP without losing backwards compatibility, and potentially breaking lots of applications. This saw it then be surpassed by faster-moving alternatives such as Symfony and even FuelPHP, which was developed as a response to CodeIgniter’s unwillingness to embrace change.
Enter: Laravel.Laravel joined the framework scene when there were already many players. However, the developers of Laravel used this timing to their advantage,
instead creating a framework that avoided all of the problems and mistakes previous full stack frameworks had made and building on top of the excellent Symfony components in order to create a robust, component-based framework.
Instead of providing dozens of inflexible libraries, Laravel provides sensible,
driver-based components that developers could use to build applications their own way, rather than trying to mash everything into the layout the framework author defined. This led to Laravel rising in popularity. It was also a fast-moving framework, and, by version 4, had become the most starred framework on GitHub, a testament to its popularity.
This book will give you a tour of Laravel and its core features. We’ll look at how to manage multiple Laravel applications on the same machine and then we’ll go ahead and start building our own Laravel application from scratch through to completion.
Once we’ve got a basic application reading and writing data from a database, we’ll take a look at Eloquent, Laravel’s ORM, which is what makes it easy to read and write from a database and the more advanced features it offers. From there, we’ll look at Artisan, Laravel’s command-line utility, and even how to define our own commands. We’ll then learn how to write automated tests for our application to make sure it keeps working the way we want it to, even with future developments. Then, finally, we’ll look at how to build login and registration systems using Laravel’s user authentication component.
By the end of the book, you’ll have a complete Laravel application, as well as the tools and knowledge of how to build your own Laravel-based applications unassisted, and where to continue your learning of the framework.

Laravel 5.1 Beauty

Laravel 5.1 Beauty

Creating Beautiful Web Apps with Laravel 5.1
by Chuck Heintzelman

Long Term Support
Laravel version 5.1 is the first LTS (long term support) Laravel release. This means bug fixes are provided for 2 years and security fixes are provided for 3 years.
This is important because the applications you build today will still be supported by the framework tomorrow.
Why This Book
My previous book on Laravel, Getting Stuff Done with Laravel 4 was well received.
Now that Laravel 5.1 is available, I briefly thought of updating my previous book to work with Laravel 5.1. The new version of Laravel implements big changes from Laravel 4, but Laravel 5.1 is mostly backwards compatible.
But the Getting Stuff Done with Laravel 4 book isn’t really a manual covering every aspect of Laravel 4. It’s a process and design book. The principles discussed within that book still are valid in Laravel 5.1, even if the implementation may vary slightly.
Instead of updating my previous book, I’ve created a new book, Laravel 5.1 Beauty, to highlight some of the new features. This book is bigger and better than Getting Stuff Done with Laravel 4.
GitHub and the Blog
I’m publishing Laravel 5.1 Beauty simultaneously, as it is being built, on my web site
LaravelCoding.com and on Leanpub.