Laravel Security
Category Archives: Laravel Tutorial
Laravel Redirections
What is Redirection?
Redirect responses are used to redirect the user from one URL to another URL. In Laravel, simplest way to return redirect response is to use global “redirect” helper method.
Redirecting To Named Routes
If you want to generate a RedirectResponse to a named route, it can be done using “route” method in following way –
Syntax:-
|
1 |
return redirect()->route('routeAlias',[params]); |
Example:-
|
1 |
return redirect()->route('dashboard'); |
If you are redirecting a route that expects parameter, we can pass them in second argument of the “route” method.
|
1 |
return redirect()->route('dashboard', ['role' => 'admin']); |
Redirecting To Controller Actions
If you want to return a redirect response to a controller action, it can be done using “action” method. Keep in mind to pass controller and action to it.
Syntax:-
|
1 |
return redirect()->action('ControllerName@actionName',[params]); |
Example:-
|
1 |
return redirect()->action('UserController@dashboard'); |
If you are redirecting a route that expects parameter, we can pass them in second argument of the “action” method.
|
1 |
return redirect()->action('UserController@dashboard', ['role' => 'admin']); |
Redirecting With Flashed Data
It is also possible in Laravel to pass flash session data while redirecting to a route, flash session data is availble upto only one redirect.
Example:-
|
1 |
return redirect('dashboard')->with('status', 'Profile updated!'); |
Laravel Eloquent ORM
What is Eloquent ORM?
One of the most important feature of the laravel framework is that, it comes with built in ORM (Object Relation Mapping) called Eloquent ORM.
Eloquent ORM refer to an advanced implementation of the PHP Active Record Pattern, which makes it very easy to interact with application database. Eloquent ORM is the very powerful yet very expressive ORM, which allow us to work with the database objects and relationships using much eloquent and expressive syntax. In Laravel, each database table is mapped into corresponding eloquent model and each of the eloquent model object include various methods for retrieving and updating the database.
Eloquent ORM CRUD Operations
Eloquent ORM makes it incredibly easy to perform CRUD (Create, Read, Update, Delete) operations on Laravel Model, since we have already covered how to create Laravel Model in previous article, so we will create new “Post” model using following artisan command –
|
1 |
php artisan make:model Post |
Let’s open the newly generated model file, at this point your model should look like as following –
|
1 2 3 4 5 6 7 8 9 10 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // } |
just edit your model as following –
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $primaryKey = 'id'; protected $table= 'posts'; protected $fillable = ['title','body','published','hits','created_at','updated_at']; } |
Eloquent ORM Create
To insert a record in database table we need to create a model instance, set or assign attributes values and then call save() method as following –
|
1 2 3 4 5 6 7 |
$post = new Post; $post->title = 'First Laravel Post'; $post->body = 'This is my first laravel article'; $post->save() |
In Laravel, we have two other methods to insert a record in database table(firstOrCreate and firstOrNew). The firstOrCreate method will try to retrieve the record matching to the column value pair. If the record not found in the table, a record will be inserted with the given column value pair. similarly, firstOrNew method method will try to retrieve the record matching to the column value pair. If the record not found in the table, a new model instance will be created with the given column value pair then you need to call save method to save the record.
|
1 2 3 4 5 |
// Retrieve the post by the attributes, or create it if it doesn't exist... $post= App\Post::firstOrCreate(['title' => 'Laravel 5']); // Retrieve the post by the attributes, or instantiate a new instance... $post= App\Post::firstOrNew(['title' => 'Laravel 5']); |
Eloquent ORM Read
Retrieving all records
In Laravel, all records can be retrieved from a table using all() method as following –
|
1 |
$posts= App\Post::all(); |
and you can loop through resultset for individual records as following –
|
1 2 3 |
foreach ($posts as $post) { echo $post->title; } |
Using Where Clause
|
1 |
$posts= App\Post::where('id', 1)->get(); |
Where Clause with Additional Constraints
|
1 2 3 |
$posts= App\Post::where('published', 1) ->orderBy('title', 'desc') ->get(); |
Retrieving Single Records
In Laravel, single record can be retrieved using find() and first() method as following –
|
1 2 3 4 5 |
// Retrieve a record by primary key... $post= App\Post::find(1); // Retrieve the first record matching the query constraints... $post= App\Post::where('published', 1)->first(); |
Record Not Found Exceptions
In Laravel, the findOrFail() and firstOrFail() methods retrieves the first result of the query and if record is not found an exception is thrown.
|
1 2 3 |
$post= App\Post::findOrFail(1); $post= App\Post::where('hits', '>', 5000)->firstOrFail(); |
Retrieving Aggregates
In Laravel, you can use aggregate functions like count, min, max, avg, sum etc. as following –
|
1 2 3 |
$published_count= App\Post::where('published', 1)->count(); $max_hits = App\Post::where('published', 1)->max('hits'); |
Eloquent ORM Update
To update a record you have to retrieve it first, set values for attributes that you want to update, and then call the save method.
|
1 2 3 4 5 |
$post= App\Post::find(1); $post->body= 'This is my first post'; $post->save(); |
Eloquent ORM Delete
To delete a record in laravel, simply call the delete method as following –
|
1 2 |
$post = App\Post::find(1); $post->delete(); |
You can delete a record directly using destroy method instead of retrieving it first, to do so simply call destroy method passing single or multiple primary keys as following –
|
1 2 3 4 5 |
App\Post::destroy(1); App\Post::destroy([1, 2, 3]); App\Post::destroy(1, 2, 3); |
You can also call delete method on query result set as following –
|
1 |
$deletedPosts = App\Post::where('published', 0)->delete(); |
Mass assignment
Laravel model allow us to assign multiple attributes values while creating model instance using the mass assignment. In Laravel model using the $fillable property we can declare array of attributes that is mass-assignable. For security concern Laravel supports a $guarded property which declare array of attributes that you do not want to be mass assignable.
Example:-
|
1 2 3 4 5 6 |
class User extends Model { protected $fillable = ['name', 'email']; protected $guarded = ['id', 'password']; } |
Soft Deleting
In Laravel, a soft deleted record is not actually removed from your database instead a deleted_at attribute is set for that record. Records with non-null deleted_at value are considered as soft deleted. To enable soft deletes for a laravel model, simply use the Illuminate\Database\Eloquent\SoftDeletes trait on the model and add the deleted_at column to your $dates property.
Example:-
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; // import SoftDeletes trait use Illuminate\Database\Eloquent\SoftDeletes; class Post extends Model { // using the SoftDeletes trait use SoftDeletes; protected $table = 'posts'; protected $dates = ['deleted_at']; protected $fillable = ['title','body']; } |
Including Soft Deleted Models
By default soft deleted records are not included in the query result-set. However, if you want to include soft deleted records in query result, it can be done using withTrashed method in query.
Example:-
|
1 2 3 |
$posts = App\Post::withTrashed() ->where('published', 1) ->get(); |
Retrieving Only Soft Deleted Models
If you want to retrieve soft deleted records only, it can be done using onlyTrashed method as following –
Example:-
|
1 2 3 |
$posts = App\Post::onlyTrashed() ->where('published', 1) ->get(); |
Determine if Soft Deleted
If you want to check if a record has been soft deleted or not, use the trashed method as following –
|
1 2 3 4 |
if($post->trashed()) { // } |
Restoring Soft Deleted Models
Soft deleted record can also be recovered using restore method as following –
|
1 2 3 |
App\Post::onlyTrashed() ->where('published', 1) ->restore(); |
Permanently Deleting Models
If you want to permanently remove a soft deleted record from the database, it can be done using forceDelete method as following –
Example 1:-
|
1 |
$post->forceDelete(); |
Example 2:-
|
1 |
App\Post::onlyTrashed()->find(10)-> forceDelete(); |
Laravel Facades
Laravel Facades
Laravel Event Handling
Laravel Event Handling
Laravel Error Handling
Laravel Error Handling
Laravel Ajax
Laravel Ajax
Laravel Sending Email
Laravel Sending Email
Laravel File Uploading
Laravel File Uploading
Laravel Session
What is Session?
In Laravel, session is a parameter passing mechanism which enable us to store data across multiple requests. Session allows us to keep track of visitor across application. Laravel uses a driver based system for session management, each of the driver is used to define where the session data will be stored. Laravel framework have following in-built session drivers –
file – Session data is stored in an encrypted file located at storage/framework/sessions.
cookie – Session data is stored in secure and encrypted user’s cookies.
database – Session data is stored in application database.
apc – Session data is stored in APC.
memcached – Session data is stored in Memcached.
redis – Session data is stored in Redis.
array – Session data is stored in a PHP array, but it is not persisted across the requests.
Laravel session configuration file is located at “app/config/session.php“. If you don’t specified your session driver, then by default file driver is used.
Storing Data In The Session
Using put method of Request instance we can store data in the session, it accepts two arguments the “key” and “value“.
Syntax:-
|
1 |
$request->session()->put('key','value'); |
Example:-
|
1 |
$request->session()->put('name','john'); |
Retrieving Value from Session
Using get method of Request instance we can retrieve a single value from the session, it accepts two arguments the “key_name” and “default_value“.
Syntax:-
|
1 |
$value = $request->session()->get('key_name'); |
OR
|
1 |
$value = $request->session()->get('key_name', 'default_value'); |
Second argument of the get method is the default value which will be returned if your specified key does not exist in the session.
Example:-
|
1 |
$name= $request->session()->get('name'); |
Retrieving All Session Data
Using all method of Request instance we can retrieve all the available data in the session.
Syntax:-
|
1 |
$all_data=$request->session()->all(); |
Checking If an Item Exists In Session
Using has method you can determine if a value is present in the session, it returns true if the value is present in the session and null if doesn’t present.
Syntax:-
|
1 2 3 |
if($request->session()->has('key_name')){ // } |
Example:-
|
1 2 3 |
if($request->session()->has('name')){ // statements to be executed if name exists } |
Deleting Data from session
Using forget method you can remove the specified item from the session, it accepts “key” as argument.
Syntax:-
|
1 |
$request->session()->forget('key'); |
If you want to retrieve an item value before deleting it from the session, you can use the pull method.
Syntax:-
|
1 |
$value = $request->session()->pull('key','default'); |
If you want to remove all items from the session, you can do it using flush method.
Syntax:-
|
1 |
$request->session()->flush(); |
Add Array In Session
If you want to add array into session, you can do it using push method as following –
Syntax:-
|
1 |
$request->session()->push('key', $arr_var); |
Example:-
|
1 2 |
$usr= array("name=> "Peter","email"=> "peter@w3adda.com", "ID"=> "135"); $request->session()->push('user_info', $usr); |
Regenerating Session ID
If you want to regenerate the session ID, you can do it using regenerate method.
|
1 |
$request->session()->regenerate(); |
Flash Data
If you want to store items in the session that will be available for only next request.You can do it using the flash method, flash data is available only for the subsequent HTTP request, and then will be deleted.
Syntax:-
|
1 |
$request->session()->flash('key', 'value'); |
Example:-
|
1 |
$request->session()->flash('status', 'Task was successful!'); |
Laravel Cookie
Creating Cookie
In Laravel, cookies are created using the withCookie() method of a response instance of Illuminate\Http\Response class. All the Cookies generated by the laravel framework are encrypted and signed using an authentication token so that they can’t be modified by the client.
Syntax:-
|
1 2 3 4 5 6 7 |
//Call the withCookie() method with the response instance $response = new Illuminate\Http\Response('Hello World'); $response->withCookie('name', 'value', $minutes); return $response; |
Retrieving Cookie
Once a cookie is created, it can be retrieved from the request using the cookie method on the Illuminate\Http\Request instance.
Syntax:-
|
1 |
$value = $request->cookie('cookie_name'); |
Laravel Blade Template
Blade is the in built templating engine for Laravel framework.Blade is a very powerful and easy to use templating engine that makes writing syntax very easy and readable. Blade templating engine comes with its own control structure such as conditional statements and loops. It is very easy to create a Blade template, simply create your view file and save it with the .blade.php extension instead of .php, blade templates are typically stored in the resources/views directory. The main advantage of using blade template engine is that it allow use to create master template which can be extended by other individual pages.
Echoing data
If you want to display any variable inside blade view, you can do it be simply wrapping the variable in “curly” braces.
Syntax:-
|
1 |
{{ $variable }} |
Above syntax is equivalent to <?= $variable ?> in plain PHP
Ternary Operator
Blade provide a short-cut equivalent to ternary operator in PHP
Syntax:-
|
1 |
{{ $variable or 'Default Value' }} |
Above syntax is equivalent to <?= isset($variable) ? $variable: ‘Default Value’ ?>
Blade Template Control Statements
The Blade template engine comes with convenient short-cuts for using PHP control statements.
Blade If Statements
Blade template engine provides the @if, @elseif, @else and @endif directives to construct equivalent PHP if statement and its counterparts.
Example:-
|
1 2 3 4 5 6 7 |
@if (count($posts) === 1) Single post! @elseif (count($blogposts) > 1) Multiple posts! @else No post found! @endif |
Blade also provides an @unless directive as a conditional statement.
Example:-
|
1 2 3 |
@unless (Auth::check()) You are not signed in. @endunless |
Blade also provides an @hasSection directive to determine if a given section has any content or not.
Example:-
|
1 2 3 4 5 6 7 |
<title> @hasSection ('title') @yield('title') - Web App Name @else Web App Name @endif </title> |
Blade Loops
Blade template engine provides @for, @endfor, @foreach, @endforeach, @while and @endwhile directives to construct equivalent PHP loop statements .
|
1 2 3 4 5 6 7 8 9 10 11 |
@for ($i = 0; $i < 10; $i++) The current value of i is {{ $i }} @endfor @foreach ($posts as $post) <p>{{ $post->title }}</p> @endforeach @while (true) <p>I'll keep looping!</p> @endwhile |
Including other views
Blade template engine provides @include(‘viewname’) directive for including a view inside another view. The child view will have all the variables that are available to parent view.
Example:-
|
1 |
@include('view.name') |
Defining a Master layout
As we know most of the web applications follows the same layout across all the pages, so the better approach is to define a master template where we can place all the boilerplate.In Laravel, blade template engine allow us to define a master template which can be extended by other individual pages.
Example:-
Step 1:- Create a new folder “layout” in /resources/views/ directory.
Step 2:- Create a new file “master.blade.php” in /resources/views/layouts/ directory.
Step 3:- Copy the following code in the “master.blade.php” file we created.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<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> |
Here, in the above master template –
@yield(‘title’) is used to display the value of the title
@section(‘sidebar’) is used to define a section named sidebar
@show is used to display the contents of a section
@yield(‘content’) is used to display the contents of content
Extending Master Layout
We will now show you how to extend the master layout we just created.
Step 1:- Create a new view file page.blade.php in /resources/views/
Step 2:- Copy the following code in page.blade.php file
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!-- path: resources/views/page.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 |
Here, in the above page –
@extends(‘layouts.master’) extends the master layout
@section(‘title’, ‘Page Title’) sets the value of the title section.
@section(‘sidebar’) defines a sidebar section in the child page of master layout
@parent displays the content of the sidebar section, defined in the master layout.
<p>This is appended to the master sidebar.</p> adds paragraph content to the sidebar section
@endsection ends the sidebar section
@section(‘content’) defines the content section
@endsection ends the content section
Step 3:– Open app/Http/routes.php and configure the route as below –
|
1 2 3 |
Route::get('page', function(){ return view('page'); }); |
Step 4:- Now open the following URL in the browser to see the output.
http://localhost:8000/page
