Getting Started

Installation

Install Composer:
sudo apt-get update
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
Install Laravel Installer for Composer:
composer global require "laravel/installer"
export PATH="~/.composer/vendor/bin:$PATH"
# OR for Mac OSX
sudo nano /etc/paths
/Users/me/.composer/vendor/bin
Create a Laravel Project with latest version (dist):
composer create-project --prefer-dist laravel/laravel website1
OR
Create a Laravel Project with latest stable version (Fast Method):
laravel new website1
Make directories writable:
cd website1
sudo chmod -R 777 storage/ bootstrap/

Installation of Git Repository

Clone the repository

git clone https://github.com/gdbhosale/lamgmt1.git
composer install
php artisan key:generate

Use last command if it gives error like: No supported encrypter found. The cipher and / or key length are invalid.

Other Useful Commands:

Check Laravel version

php artisan --version

Check Laravel Installer version

laravel --version

Artisan Commands

Artisan is command-line interface included in Laravel from Symfony Console component.

List of all Artisan commands:
php artisan list
List of all Artisan commands under make section:
php artisan list make
Help regarding Artisan commands:
php artisan help make:auth

Artisan Make Commands

Command Description Usage
make:auth Scaffold basic login and registration views and routes php artisan make:auth
make:console Create a new Artisan command php artisan make:console SendEmails --command=emails:send Help
make:controller Create a new controller class php artisan make:controller BookController
make:event Create a new event class
make:job Create a new job class
make:listener Create a new event listener class
make:middleware Create a new middleware class
make:migration Create a new migration file php artisan make:migration create_books_table
make:model Create a new Eloquent model class php artisan make:model Book
make:policy Create a new policy class
make:provider Create a new service provider class
make:request Create a new form request class php artisan make:request PublishBookRequest
make:seeder Create a new seeder class
make:test Create a new test class

Artisan Migrate Commands

Command Description Usage
migrate Run the database migrations php artisan migrate
migrate:install Create the migration repository php artisan migrate:install
migrate:refresh Reset and re-run all migrations php artisan migrate:refresh
migrate:reset Rollback all database migrations php artisan migrate:reset
migrate:rollback Rollback the last database migration php artisan migrate:rollback
migrate:status Show the status of each migration php artisan migrate:status

Artisan Route Commands

Command Description Usage
route:cache Create a route cache file for faster route registration php artisan route:cache
route:clear Remove the route cache file php artisan route:clear
route:list List all registered routes php artisan route:list

More Artisan Commands

Command Description Usage
view:clear Clear all compiled view files php artisan view:clear
clear-compiled Remove the compiled class file php artisan clear-compiled
key:generate Set the application key php artisan key:generate
#TODO: Add more commands here after testing

Blade Template Engine

Templating

Why Blade ?
  • Template Inheritance
  • Sections
  • Compiled Layouts for performance
  • Reduce code

Defining Layout resources/views/layouts/master.blade.php

<html>
    <head>
        <title>App Name - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            This is the master sidebar.
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

Extending A Layout resources/views/child.blade.php

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
    @parent

    <p>This is appended to the master sidebar.</p>
@endsection

@section('content')
    <p>This is my body content.</p>
@endsection

Load view using routes

Route::get('blade', function () {
    return view('child');
});
Passing data in view
return view('child', ['name' => 'Virat']);

Templating Commands

Command Description Usage
{{ $var }} Echo content. Also prevents XSS attacks
{{ $user->id }}
{{ $var or 'default' }} Echo content with a default value
{{ $name or 'John Doe' }}
@{{ var }} Echo content. Bypass JavaScript frameworks
@{{ name }}
{{{ $var }}} Echo escaped content
{{-- Comment --}} A Blade comment
@extends('layout') Extends a template with a layout
@extends('layouts.master')
@if(condition) Starts an if block
@if (count($records) === 1)
    I have one record!
@elseif (count($records) > 1)
    I have multiple records!
@else
    I don't have any records!
@endif
@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
@foreach ($users as $user)
    <p>{{ $user->name }}</p>
@endforeach
@endforeach Ends a foreach block
@for($i = 0; $i < 10; $i++) Starts a for block
@for ($i = 0; $i < 10; $i++)
    i = {{ $i }}
@endfor
@endfor Ends a for block
@while(condition) Starts a while block
@while (true)
    <p>looping forever.</p>
@endwhile
@endwhile Ends a while block
@unless(condition) Starts an unless block
@unless (Auth::check())
    You are not signed in.
@endunless
@endunless Ends an unless block
@forelse($list as $key => $val) Starts an unless block
@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <li>No users</li>
@endforelse
@empty If empty the do this
@endforelse End the forelse Block
@break Break out of for loop
@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach
@continue Continue for loop
@include(file) Includes another template
@include('shared.errors')
@include(file, ['var' => $val,...]) Includes a template, passing new variables.
@include('view.name', ['some' => 'data'])
@each('file',$list,'item') Renders a template on a collection
@each('view.name', $jobs, 'job')
@each('file',$list,'item','empty') Renders a template on a collection or a different template if collection is empty.
@each('view.name', $jobs, 'job', 'view.empty')
@yield('section') Yields content of a section.
@hasSection('title')
    @yield('title') - App Name
@else
    App Name
@endif
@push Allows you to push to named stacks which can be rendered somewhere else in another view or layout
@push('scripts')
 <script src="/example.js"></script>
@endpush
<head>
    <!-- Head Contents -->

    @stack('scripts')
</head>
@endpush
@stack
@lang('message') Outputs message from translation table
@choice('message', $count) Outputs message with language pluralization
@section('name') Starts a section
@stop Ends section
@show Ends section and yields its content
@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

Basic CRUD

Database Migration

Once we create the basic project in Laravel, We need authetication for CRUD.

php artisan make:auth

Now create a database and link it in .env

DB_DATABASE=crud1
DB_USERNAME=root
DB_PASSWORD=root

After linking databse we will use migrate commands to create tables automatically.

php artisan migrate

Routing & Controller

Create Controller as Resource:

Let's create the controller for our CRUD: BookController. Which will do Creation, Reading, Updation and Deletion of Books.

php artisan make:controller BookController --resource
Create a Route in app/Http/routes.php:

Now we need to create Routing for the BookController as a resource. Add below line at end of file.

Route::resource('book', 'BookController');

To validate that BookController will work correctly, use following command to get all routes of application.

$ php artisan route:list
+--------+-----------+-------------------------+--------------+-----------------------------------------------------------------+------------+
| Domain | Method    | URI                     | Name         | Action                                                          | Middleware |
+--------+-----------+-------------------------+--------------+-----------------------------------------------------------------+------------+
|        | GET|HEAD  | /                       |              | Closure                                                         | web        |
|        | GET|HEAD  | book                    | book.index   | App\Http\Controllers\BookController@index                       | web        |
|        | POST      | book                    | book.store   | App\Http\Controllers\BookController@store                       | web        |
|        | GET|HEAD  | book/create             | book.create  | App\Http\Controllers\BookController@create                      | web        |
|        | GET|HEAD  | book/{book}             | book.show    | App\Http\Controllers\BookController@show                        | web        |
|        | DELETE    | book/{book}             | book.destroy | App\Http\Controllers\BookController@destroy                     | web        |
|        | PUT|PATCH | book/{book}             | book.update  | App\Http\Controllers\BookController@update                      | web        |
|        | GET|HEAD  | book/{book}/edit        | book.edit    | App\Http\Controllers\BookController@edit                        | web        |
|        | GET|HEAD  | home                    |              | App\Http\Controllers\HomeController@index                       | web,auth   |
|        | GET|HEAD  | login                   |              | App\Http\Controllers\Auth\AuthController@showLoginForm          | web,guest  |
|        | POST      | login                   |              | App\Http\Controllers\Auth\AuthController@login                  | web,guest  |
|        | GET|HEAD  | logout                  |              | App\Http\Controllers\Auth\AuthController@logout                 | web        |
|        | POST      | password/email          |              | App\Http\Controllers\Auth\PasswordController@sendResetLinkEmail | web,guest  |
|        | POST      | password/reset          |              | App\Http\Controllers\Auth\PasswordController@reset              | web,guest  |
|        | GET|HEAD  | password/reset/{token?} |              | App\Http\Controllers\Auth\PasswordController@showResetForm      | web,guest  |
|        | GET|HEAD  | register                |              | App\Http\Controllers\Auth\AuthController@showRegistrationForm   | web,guest  |
|        | POST      | register                |              | App\Http\Controllers\Auth\AuthController@register               | web,guest  |
+--------+-----------+-------------------------+--------------+-----------------------------------------------------------------+------------+

After getting such output for BookController you might have understood that routes assumes the default CRUD methods.

Let's edit the app\Http\Controllers\BookController.php and view/edit the respective methods.

To take this section Book under authentication (Optional), We need to add authentication in constructor like below:

    public function __construct()
    {
        $this->middleware('auth');
    }

After doing this you can see change in routes. All Book Methods get auth as Middleware.

Creating Models

Let's move ahead and create model using following command:

php artisan make:model -m Book

Extra argument -m will generate migration database/migrations/2016_05_16_114615_create_books_table.php

To explicitly create migration, You can use: php artisan make:migration create_books_table


Edit Model:
class Book extends Model
{
    protected $table = 'books';
    protected $fillable = [
        'title',
        'description',
        'author',
        'price'
    ];
}

Edit migration file database/migrations/2016_05_16_114615_create_books_table.php to create fields in table.

    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->string('author');
            $table->integer('price');
            $table->timestamps();
        });
    }

Now generate the DB tables automatically.

php artisan migrate

Data Validation (Optional):

Now we need validation rules for data. So we create Request to do so.

php artisan make:request PublishBookRequest

This will generate app/Http/Requests/PublishBookRequest.php. Edit it as below:

    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'title' => 'required',
            'author' => 'required',
            'price' => 'required'
        ];
    }

CRUD Methods

1. Record Listing

Link Book Model in BookController (Before class defination):

use App\Book;

Edit index method in BookController as below:

    public function index() {
        $allBooks = Book::all(); // Selects all Books inside table.
        return View('books.bookList', compact('allBooks'));
    }

Lets create a view file: resources/views/books/bookList.blade.php. Need to create books folder.

@extends('layouts.app')
@section('content')
<div class="container">
    <a class="btn btn-primary btn-sm pull-right" href="{{ route('book.create') }}">Add New Book</a><br><br>
    
    <div class="list-group">
    @foreach( $allBooks as $book )
        <div class="list-group-item">
            {!! Html::linkRoute('book.show', $book->title, array($book->id)) !!} ({{$book->author }})
            <span class="pull-right">
                {!! Html::linkRoute('book.edit', 'Edit', array($book->id), ['class'=>'btn btn-success btn-xs', 'style'=>'display:inline']) !!}
                {!! Form::open(['route' => ['book.destroy', $book->id], 'method' => 'delete', 'style'=>'display:inline']) !!}
                <input class="btn btn-danger btn-xs" type="submit" value="Delete" />
                {!! Form::close() !!}
            </span>
        </div>
    @endforeach
    </div>
</div>
@endsection

This will create a view without data. Later on it will look like below:

Laravel CRUD - Record Listing

2. Create Record

Add PublishBookRequest in BookController:

use App\Http\Requests\PublishBookRequest;

Edit create & store methods in BookController as below:


    public function create()
    {
        return view('books.addBook');
    }
	
    public function store(PublishBookRequest $request)
    {
        // Insert Query
        $book = new Book;
        $book->title= $request['title'];
        $book->description= $request['description'];
        $book->author= $request['author'];
        $book->price= $request['price'];
        $book->save();

        // Send control to index() method where it'll redirect to Book-List
        return redirect()->route('book.index');
    }

Form and HTML Libraries:

Before creating Forms in Add Book, we need to add few Libraries like Form and HTML.
It is included in package laravelcollective/html. Use command:

composer require laravelcollective/html

Now open and edit config/app.php as below.

'providers' => [
    ...
    Collective\Html\HtmlServiceProvider::class,
],
'aliases' => [
    ...
    'Form' => Collective\Html\FormFacade::class,
    'Html' => Collective\Html\HtmlFacade::class
],
Create add view file resources/views/books/addBook.blade.php:
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1>Add New Book</h1>
            {!! Form::open(['action' => 'BookController@store']) !!}
				
                <div class="form-group">
                    {!! Form::label('title', 'Title :') !!}
                    {!! Form::text('title', null, ['class'=>'form-control', 'placeholder'=>'Enter Title']) !!}
                </div>

                <div class="form-group">
                    {!! Form::label('description', 'Description :') !!}
                    {!! Form::textarea('description', null,  ['class'=>'form-control', 'placeholder'=>'Description']) !!}
                </div>

                <div class="form-group">
                    {!! Form::label('author', 'Author name :') !!}
                    {!! Form::text('author', null,  ['class'=>'form-control', 'placeholder'=>'Author Name']) !!}
                </div>
				
                <div class="form-group">
                    {!! Form::label('price', 'Price :') !!}
                    {!! Form::text('price', null,  ['class'=>'form-control', 'placeholder'=>'Price']) !!}
                </div><br>
                
                <div class="form-group">
                    {!! Form::submit( 'Submit', ['class'=>'btn btn-success']) !!} <a class="btn btn-default pull-right" href="{{ url('/book') }}">Back to Home</a>
                </div>
            {!! Form::close() !!}
            @if($errors->any())
                <ul class="alert alert-danger">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            @endif
        </div><br>
    </div><br>
</div><br>
@endsection

This is How form will look.

Laravel CRUD - Create Add Form

3. Display Record:

Edit show method in BookController as below:

    public function show($id)
    {
        $book = Book::find($id);
        return view('books.showBook')->with('book',$book);
    }
Create show view file resources/views/books/showBook.blade.php:
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="row col-xs-8 col-xs-offset-2 img-rounded text-center" style="background-color:#eee;">
            <div><h2>{{ $book->title }}</h2></div><br>
            <div>{{ $book->description }}</div><br>
            <div class="pull-left"><b>Cost:</b> ${{ $book->price }}</div>
            <div class="blockquote-reverse">Published by - {{ $book->author }}</div>
            <br><a class="btn btn-default" href="{{ url('/book') }}">Back to Home</a><br><br>
        </div><br>
    </div><br>
</div><br>
@endsection

Laravel CRUD - Show Record

4. Update Record:

Edit edit method in BookController as below:

    public function edit($id)
    {
        $book = Book::find($id);
        return view('books.editBook')->with('book',$book);
    }
	
	public function update(Request $request, $id)
    {
        $book = Book::find($id);

        //Update Query
        $book->title = $request['title'];
        $book->description = $request['description'];
        $book->author = $request['author'];
		$book->price = $request['price'];
        $book->save();

        //Redirecting to index() method of BookController class
        return redirect()->route('book.index');
    }
Create edit view file resources/views/books/editBook.blade.php:
@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1>Edit {{ $book->title }}</h1>
            {!! Form::model($book, ['route' => ['book.update', $book->id ], 'method'=>'PUT']) !!}
            <div class="form-group">
                {!! Form::label('title', 'Title :') !!}
                {!! Form::text('title', null, ['class'=>'form-control', 'placeholder'=>'Enter Title']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('description', 'Description :') !!}
                {!! Form::textarea('description', null,  ['class'=>'form-control', 'placeholder'=>'Description']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('author', 'Author name :') !!}
                {!! Form::text('author', null,  ['class'=>'form-control', 'placeholder'=>'Author Name']) !!}
            </div>

            <div class="form-group">
                {!! Form::label('price', 'Price :') !!}
                {!! Form::text('price', null,  ['class'=>'form-control', 'placeholder'=>'Price']) !!}
            </div><br>

            <div class="form-group">
                {!! Form::submit( 'Update', ['class'=>'btn btn-success']) !!} <a class="btn btn-default pull-right" href="{{ url('/book') }}">Back to Home</a>

            {!! Form::close() !!}
            @if($errors->any())
                <ul class="alert alert-danger">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            @endif
        </div><br>
    </div><br>
</div><br>
@endsection

Laravel CRUD - Edit Record

5. Delete Record:

Edit destroy method in BookController as below:

    public function destroy($id)
    {
        Book::find($id)->delete();

        // Redirecting to index() method for Listing
        return redirect()->route('book.index');
    }

We have already created the destroy form in listing:

{!! Form::open(['route' => ['book.destroy', $book->id], 'method' => 'delete', 'style'=>'display:inline']) !!}
	<input class="btn btn-danger btn-xs" type="submit" value="Delete" />
{!! Form::close() !!}

MongoDB in Laravel

Installation

Install MongoDB on Mac OSX:
brew update
brew install mongodb
sudo mkdir -p /data/db
sudo chmod -R 777 /data/db/
Install MongoDB Extension/Drivers for PHP for Mac OSX (Help):
brew install homebrew/php/php55-mongodb
Install MongoDB Extension/Drivers for PHP for Ubuntu (Help):
sudo pecl install mongodb
Add to PATH:
export PATH=/usr/local/opt/php55-mongodb/:$PATH
cp /usr/local/opt/php55-mongodb/mongodb.so /Applications/MAMP/bin/php/php5.5.14/lib/php/extensions/no-debug-non-zts-20121212
Add to php.ini:
sudo nano  /etc/php5/apache2/php.ini

# Add this line in php.ini
extension=mongodb.so

Test your installation by calling phpinfo();. Make sure mongodb is visible there.

Start MongoDB Server

To start mongodb server command is:

mongod

This will start MongoDB server.

MongoDB command-lines; Create root user:

You can also access MongoDB through command-lines using command mongo as below.

mongo
use admin
db.createUser({user:"root",pwd:"root",roles:["root"]})

MongoDB integration in Laravel using library: jenssegers/mongodb

Install library using composer:
composer require jenssegers/mongodb
edit config/app.php:
'providers' =>
	Jenssegers\Mongodb\Auth\PasswordResetServiceProvider::class,
'aliases' =>
	'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
Configure Database in config/database.php. Add new connection:
    'mongodb' => [
        'driver'   => 'mongodb',
        'host'     => env('DB_HOST', 'localhost'),
        'port'     => "27017",
        'database' => 'admin',
        'username' => 'root',
        'password' => 'root',
        'options' => [
            'database' => 'admin' // sets the authentication database required by mongo 3
        ]
    ],

Using MongoDB

Lets start using MongoDB models Moloquent:

php artisan make:model Book
Book.php
namespace App;
use Moloquent;

class Book extends Moloquent {
    protected $collection = 'book_collection';
    protected $connection = 'mongodb';
}
Access model in HomeController.php
use App\Book;

public function index() {
    
    // $book = new Book;
    // $book->name = 'LOTR';
    // $book->save();
    
    $books = Book::all();
    
    return View('home', compact('books'));
}