Laravel
Compressed Guide / Cheetsheet
Compressed Guide / Cheetsheet
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
ORlaravel new website1
Make directories writable:
cd website1
sudo chmod -R 777 storage/ bootstrap/
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.
Check Laravel version
php artisan --version
Check Laravel Installer version
laravel --version
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
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 |
|
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 |
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 |
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 |
Route::get('blade', function () {
return view('child');
});
Passing data in view
return view('child', ['name' => 'Virat']);
Command | Description | Usage |
---|---|---|
{{ $var }} |
Echo content. Also prevents XSS attacks |
|
{{ $var or 'default' }} |
Echo content with a default value |
|
@{{ var }} |
Echo content. Bypass JavaScript frameworks |
|
{{{ $var }}} |
Echo escaped content | |
{{-- Comment --}} |
A Blade comment | |
@extends('layout') |
Extends a template with a layout |
|
@if(condition) |
Starts an if block |
|
@else |
Starts an else block | |
@elseif(condition) |
Start a elseif block | |
@endif |
Ends a if block | |
@foreach($list as $key => $val) |
Starts a foreach block |
|
@endforeach |
Ends a foreach block | |
@for($i = 0; $i < 10; $i++) |
Starts a for block |
|
@endfor |
Ends a for block | |
@while(condition) |
Starts a while block |
|
@endwhile |
Ends a while block | |
@unless(condition) |
Starts an unless block |
|
@endunless |
Ends an unless block | |
@forelse($list as $key => $val) |
Starts an unless block |
|
@empty |
If empty the do this | |
@endforelse |
End the forelse Block | |
@break |
Break out of for loop |
|
@continue |
Continue for loop | |
@include(file) |
Includes another template |
|
@include(file, ['var' => $val,...]) |
Includes a template, passing new variables. |
|
@each('file',$list,'item') |
Renders a template on a collection |
|
@each('file',$list,'item','empty') |
Renders a template on a collection or a different template if collection is empty. |
|
@yield('section') |
Yields content of a section. |
|
@push |
Allows you to push to named stacks which can be rendered somewhere else in another view or layout |
|
@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 |
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
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.
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
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
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'
];
}
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.
This will create a view without data. Later on it will look like below:
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');
}
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
:
This is How form will look.
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
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
:
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() !!}
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.
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"]})
jenssegers/mongodb
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
]
],
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'));
}