Category Archives: Laravel Tutorial

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:-

Example:-

If you are redirecting a route that expects parameter, we can pass them in second argument of the “route” method.

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:-

Example:-

If you are redirecting a route that expects parameter, we can pass them in second argument of the “action” method.

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:-

 

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 –

Let’s open the newly generated model file, at this point your model should look like as following –

just edit your model as following –

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 –

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.

Eloquent ORM Read

Retrieving all records

In Laravel, all records can be retrieved from a table using all() method as following –

and you can loop through resultset for individual records as following –

Using Where Clause

Where Clause with Additional Constraints

Retrieving Single Records

In Laravel, single record can be retrieved using find() and first() method as following –

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.

Retrieving Aggregates

In Laravel, you can use aggregate functions like count, min, max, avg, sum etc. as following –

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.

Eloquent ORM Delete

To delete a record in laravel, simply call the delete method as following –

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 –

You can also call delete method on query result set as following –

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:-

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:-

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:-

Retrieving Only Soft Deleted Models

If you want to retrieve soft deleted records only, it can be done using onlyTrashed method as following –

Example:-

Determine if Soft Deleted

If you want to check if a record has been soft deleted or not, use the trashed method as following –

Restoring Soft Deleted Models

Soft deleted record can also be recovered using restore method as following –

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:-

Example 2:-

 

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:-

Example:-

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:-

OR

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:-

Retrieving All Session Data

Using all method of Request instance we can retrieve all the available data in the session.

Syntax:-

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:-

Example:-

Deleting Data from session

Using forget method you can remove the specified item from the session, it accepts “key” as argument.

Syntax:-

If you want to retrieve an item value before deleting it from the session, you can use the pull method.

Syntax:-

If you want to remove all items from the session, you can do it using flush method.

Syntax:-

Add Array In Session

If you want to add array into session, you can do it using push method as following –

Syntax:-

Example:-

Regenerating Session ID

If you want to regenerate the session ID, you can do it using regenerate method.

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:-

Example:-

 

Laravel 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:-

Once a cookie is created, it can be retrieved from the request using the cookie method on the Illuminate\Http\Request instance.

Syntax:-

 

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:-

Above syntax is equivalent to <?= $variable ?> in plain PHP

Ternary Operator

Blade provide a short-cut equivalent to ternary operator in PHP

Syntax:-

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:-

Blade also provides an @unless directive as a conditional statement.

Example:-

Blade also provides an @hasSection directive to determine if a given section has any content or not.

Example:-

Blade Loops

Blade template engine provides @for, @endfor, @foreach, @endforeach, @while and @endwhile directives to construct equivalent PHP loop statements .

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:-

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.

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

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 –

Step 4:- Now open the following URL in the browser to see the output.

http://localhost:8000/page