Quick Reference Study Notes for Laravel 5.x (Advanced)


Laravel 5.x

Laravel is a web application framework with classic syntax. Laravel provides common tasks used in the majority of web projects, such as authentication, routing, sessions, and caching without sacrificing application functionality.

1.Installation:

Step 1:  Installing composer-

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Step 2: Installing Laravel(using composer)-

composer global require "laravel/installer"

2.Create a project:

This command will create a project with name “my_project”:
composer create-project laravel/laravel my_project

3.Run Your Project:

php artisan serve

4.File Structure:

Element

Path

Models

my_project/app/modelname.php

Controllers

my_project/app/Http/Controllers/controllername.php

Views

my_project/resources/views/viewname.blade.php

Routes

my_project/routes/web.php

Config/App

my_project/config/app.php

Environment config

my_project/.env

   

 

 

my_project
├─app
| └─Http
|   â””─controllers
|     â””─PagesController.php
├─resources
|   â””─assets
|     â””─views
|       â”œâ”€about.blade.php
|       â””─contacts.blade.php
└─routes
|  â””─web.php
└─.env

 

5.Artisan CLI:

  • Create a Controller-

            php artisan make:controller MyController

  • Create a RESTful Resource Controller-

            php artisan make:controller MyController --resource

  • Create Model

           php artisan make:model MyModel

  • Run Migrations

           php artisan migrate

  • Flush the application cache

           php artisan cache:clear

  • Create a migration for the cache database table

            php artisan cache:table

  • Create a cache file for faster configuration loading

           php artisan config:cache

  • Remove the configuration cache file

           php artisan config:clear

  • Serve the application on the PHP development server

             php artisan serve
 

  • Change the default port

            php artisan serve --port 8080

 

  1. Authentication:

Determine if the current user is authenticated- Auth::check();
Get the currently authenticated user- Auth::user();
Get the ID of the currently authenticated user- Auth::id();
Attempt to authenticate a user using the given credentials- Auth::attempt(array('email' => $email, 'password' => $password));
'Remember me' by passing true to Auth::attempt()- Auth::attempt($credentials, true);
Log in for a single request- Auth::once($credentials);
Log a user into the application- Auth::login(User::find(1));
Log the given user ID into the application- Auth::loginUsingId(1);
Log the user out of the application- Auth::logout();
Validate a user's credentials- Auth::validate($credentials);
Attempt to authenticate using HTTP Basic Auth- Auth::basic('username');
Perform a stateless HTTP Basic login attempt- Auth::onceBasic();
Send a password reminder to a user- Password::remind($credentials, function($message, $user){});

 

  1. Blade Files:

  • Show a section in a template

          @yield('name')
          @extends('layout.name')

 

  • Begin a section

           @section('name')

 

  • End a section

            @stop

 

  • End a section and yield

@section('sidebar')
@show
@parent

 

  • Echo content

{{ $var }}

 

  • Echo escaped content

{{{ $var }}}

 

  • Echo unescaped content

{!! $var !!}

{{-- Blade Comment --}}

 

  • Echoing Data After Checking For Existence

{{{ $name or 'Default' }}}

 

  • Displaying Raw Text With Curly Braces

@{{ This will not be processed by Blade }}

 

  • Others

@include('view.name')
@include('view.name', array('key' => 'value'));
@lang('messages.name')
@choice('messages.name', 1);

@if
@else
@elseif
@endif

@unless
@endunless

@for
@endfor

@foreach
@endforeach

@while
@endwhile

 


 

  1. Config:

Config::get('app.timezone');
Config::get('app.timezone', 'UTC');             //get with Default value
Config::set('database.default', 'sqlite');     //set Configuration

 

  1. Cookie:

Cookie::get('key');
Cookie::get('key', 'default');
// Create a cookie that lasts forever
Cookie::forever('key', 'value');
// Create a cookie that lasts N minutes
Cookie::make('key', 'value', 'minutes');
// Set a cookie before a response has been created
Cookie::queue('key', 'value', 'minutes');
// Forget cookie
Cookie::forget('key');
// Send a cookie with a response
$response = Response::make('Hello World');
// Add a cookie to the response
$response->withCookie(Cookie::make('name', 'value', $minutes));

 

  1. File:

File::exists('path');
File::get('path');
File::getRemote('path');
// Get a file's contents by requiring it
File::getRequire('path');
// Require the given file once
File::requireOnce('path');
// Write the contents of a file
File::put('path', 'contents');
// Append to a file
File::append('path', 'data');
// Delete the file at a given path
File::delete('path');
// Move a file to a new location
File::move('path', 'target');
// Copy a file to a new location
File::copy('path', 'target');
// Extract the file extension from a file path
File::extension('path');
// Get the file type of a given file
File::type('path');
// Get the file size of a given file
File::size('path');
// Get the file's last modification time
File::lastModified('path');
// Determine if the given path is a directory
File::isDirectory('directory');
// Determine if the given path is writable
File::isWritable('path');
// Determine if the given path is a file
File::isFile('file');
// Find path names matching a given pattern.
File::glob($patterns, $flag);
// Get an array of all files in a directory.
File::files('directory');
// Get all of the files from the given directory (recursive).
File::allFiles('directory');
// Get all of the directories within a given directory.
File::directories('directory');
// Create a directory
File::makeDirectory('path',  $mode = 0777, $recursive = false);
// Copy a directory from one location to another
File::copyDirectory('directory', 'destination', $options = null);
// Recursively delete a directory
File::deleteDirectory('directory', $preserve = false);
// Empty the specified directory of all files and folders
File::cleanDirectory('directory');

 

  1. Database:

  • Basic DB Usage-

DB::connection('connection_name');
// Running A Select Query
$results = DB::select('select * from users where id = ?', [1]);
$results = DB::select('select * from users where id = :id', ['id' => 1]);
// Running A General Statement
DB::statement('drop table users');
// Listening For Query Events
DB::listen(function($sql, $bindings, $time){ code_here; });
// Database Transactions
DB::transaction(function()
{
 DB::table('users')->update(['votes' => 1]);
 DB::table('posts')->delete();
});
DB::beginTransaction();
DB::rollback();
DB::commit();

 

  • Query Builder-

//Retrieving All Rows From A Table
DB::table('name')->get();
// Chunking Results From A Table
DB::table('users')->chunk(100, function($users)
{
 foreach ($users as $user)
 {
     //
 }
});
// Retrieving A Single Row From A Table
$user = DB::table('users')->where('name', 'John')->first();
DB::table('name')->first();
// Retrieving A Single Column From A Row
$name = DB::table('users')->where('name', 'John')->pluck('name');
DB::table('name')->pluck('column');
// Retrieving A List Of Column Values
$roles = DB::table('roles')->lists('title');
$roles = DB::table('roles')->lists('title', 'name');
// Specifying A Select Clause
$users = DB::table('users')->select('name', 'email')->get();
$users = DB::table('users')->distinct()->get();
$users = DB::table('users')->select('name as user_name')->get();
// Adding A Select Clause To An Existing Query
$query = DB::table('users')->select('name');
$users = $query->addSelect('age')->get();
// Using Where Operators
$users = DB::table('users')->where('votes', '>', 100)->get();
$users = DB::table('users')
             ->where('votes', '>', 100)
             ->orWhere('name', 'John')
             ->get();
$users = DB::table('users')
             ->whereBetween('votes', [1, 100])->get();
$users = DB::table('users')
             ->whereNotBetween('votes', [1, 100])->get();
$users = DB::table('users')
             ->whereIn('id', [1, 2, 3])->get();
$users = DB::table('users')
             ->whereNotIn('id', [1, 2, 3])->get();
$users = DB::table('users')
             ->whereNull('updated_at')->get();
DB::table('name')->whereNotNull('column')->get();
// Dynamic Where Clauses
$admin = DB::table('users')->whereId(1)->first();
$john = DB::table('users')
             ->whereIdAndEmail(2, 'john@doe.com')
             ->first();
$jane = DB::table('users')
             ->whereNameOrAge('Jane', 22)
             ->first();
// Order By, Group By, And Having
$users = DB::table('users')
             ->orderBy('name', 'desc')
             ->groupBy('count')
             ->having('count', '>', 100)
             ->get();
DB::table('name')->orderBy('column')->get();
DB::table('name')->orderBy('column','desc')->get();
DB::table('name')->having('count', '>', 100)->get();
// Offset & Limit
$users = DB::table('users')->skip(10)->take(5)->get();

 

  1. Mail

  • Baisc-

Mail::send('email.view', $data, function($message){});
Mail::send(array('html.view', 'text.view'), $data, $callback);
Mail::queue('email.view', $data, function($message){});
Mail::queueOn('queue-name', 'email.view', $data, $callback);
Mail::later(5, 'email.view', $data, function($message){});
// Write all email to logs instead of sending
Mail::pretend();

 

  • Messages-

// These can be used on the $message instance passed into Mail::send() or Mail::queue()
$message->from('email@example.com', 'Mr. Example');
$message->sender('email@example.com', 'Mr. Example');
$message->returnPath('email@example.com');
$message->to('email@example.com', 'Mr. Example');
$message->cc('email@example.com', 'Mr. Example');
$message->bcc('email@example.com', 'Mr. Example');
$message->replyTo('email@example.com', 'Mr. Example');
$message->subject('Welcome to the Jungle');
$message->priority(2);
$message->attach('foo\bar.txt', $options);
// This uses in-memory data as attachments
$message->attachData('bar', 'Data Name', $options);
// Embed a file in the message and get the CID
$message->embed('foo\bar.txt');
$message->embedData('foo', 'Data Name', $options);
// Get the underlying Swift Message instance
$message->getSwiftMessage();

 

  1. Redirect:

return Redirect::to('foo/bar');
return Redirect::to('foo/bar')->with('key', 'value');
return Redirect::to('foo/bar')->withInput(Input::get());
return Redirect::to('foo/bar')->withInput(Input::except('password'));
return Redirect::to('foo/bar')->withErrors($validator);
// Create a new redirect response to the previous location
return Redirect::back();
// Create a new redirect response to a named route
return Redirect::route('foobar');
return Redirect::route('foobar', array('value'));
return Redirect::route('foobar', array('key' => 'value'));
// Create a new redirect response to a controller action
return Redirect::action('FooController@index');
return Redirect::action('FooController@baz', array('value'));
return Redirect::action('FooController@baz', array('key' => 'value'));
// If intended redirect is not defined, defaults to foo/bar.
return Redirect::intended('foo/bar');

 

  1. Route:

Route::get('foo', function(){});
Route::get('foo', 'ControllerName@function');
Route::controller('foo', 'FooController');

 

  1. Security:

  • Hashing-

Hash::make('secretpassword');
Hash::check('secretpassword', $hashedPassword);
Hash::needsRehash($hashedPassword);

 

  • Encryption-

Crypt::encrypt('secretstring');
Crypt::decrypt($encryptedString);
Crypt::setMode('ctr');
Crypt::setCipher($cipher);

 

  1. Session:

Session::get('key');
// Returns an item from the session
Session::get('key', 'default');
Session::get('key', function(){ return 'default'; });
// Get the session ID
Session::getId();
// Put a key / value pair in the session
Session::put('key', 'value');
// Push a value into an array in the session
Session::push('foo.bar','value');
// Returns all items from the session
Session::all();
// Checks if an item is defined
Session::has('key');
// Remove an item from the session
Session::forget('key');
// Remove all of the items from the session
Session::flush();
// Generate a new session identifier
Session::regenerate();
// Flash a key / value pair to the session
Session::flash('key', 'value');
// Reflash all of the session flash data
Session::reflash();
// Reflash a subset of the current flash data
Session::keep(array('key1', 'key2'));

 

  1. URL:

URL::full();
URL::current();
URL::previous();
URL::to('foo/bar', $parameters, $secure);
URL::action('NewsController@item', ['id'=>123]);
// need be in appropriate namespace
URL::action('Auth\AuthController@logout');
URL::action('FooController@method', $parameters, $absolute);
URL::route('foo', $parameters, $absolute);
URL::secure('foo/bar', $parameters);
URL::asset('css/foo.css', $secure);
URL::secureAsset('css/foo.css');
URL::isValidUrl('http://example.com');
URL::getRequest();
URL::setRequest($request);

 

  1. View:

View::make('path/to/view');
View::make('foo/bar')->with('key', 'value');
View::make('foo/bar')->withKey('value');
View::make('foo/bar', array('key' => 'value'));
View::exists('foo/bar');
// Share a value across all views
View::share('key', 'value');
// Nesting views
View::make('foo/bar')->nest('name', 'foo/baz', $data);
// Register a view composer
View::composer('viewname', function($view){});
//Register multiple views to a composer
View::composer(array('view1', 'view2'), function($view){});
// Register a composer class
View::composer('viewname', 'FooComposer');
View::creator('viewname', function($view){});

 

  1. Validation:

Validator::make(
array('key' => 'Foo'),
array('key' => 'required|in:Foo')
);
Validator::extend('foo', function($attribute, $value, $params){});
Validator::extend('foo', 'FooValidator@validate');
Validator::resolver(function($translator, $data, $rules, $msgs)
{
return new FooValidator($translator, $data, $rules, $msgs);
});


NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."

This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. More info. I Agree