Laravel – Cookie ”; Previous Next Cookies play an important role while dealing a user’s session on a web application. In this chapter, you will learn about working with cookies in Laravel based web applications. Creating a Cookie Cookie can be created by global cookie helper of Laravel. It is an instance of SymfonyComponentHttpFoundationCookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of IlluminateHttpResponse class to call the withCookie() method. Cookie generated by the Laravel are encrypted and signed and it can’t be modified or read by the client. Here is a sample code with explanation. //Create a response instance $response = new IlluminateHttpResponse(”Hello World”); //Call the withCookie() method with the response method $response->withCookie(cookie(”name”, ”value”, $minutes)); //return the response return $response; Cookie() method will take 3 arguments. First argument is the name of the cookie, second argument is the value of the cookie and the third argument is the duration of the cookie after which the cookie will get deleted automatically. Cookie can be set forever by using the forever method as shown in the below code. $response->withCookie(cookie()->forever(”name”, ”value”)); Retrieving a Cookie Once we set the cookie, we can retrieve the cookie by cookie() method. This cookie() method will take only one argument which will be the name of the cookie. The cookie method can be called by using the instance of IlluminateHttpRequest. Here is a sample code. //’name’ is the name of the cookie to retrieve the value of $value = $request->cookie(”name”); Example Observe the following example to understand more about Cookies − Step 1 − Execute the below command to create a controller in which we will manipulate the cookie. php artisan make:controller CookieController –plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in app/Http/Controllers/CookieController.php file. app/Http/Controllers/CookieController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use IlluminateHttpResponse; use AppHttpRequests; use AppHttpControllersController; class CookieController extends Controller { public function setCookie(Request $request) { $minutes = 1; $response = new Response(”Hello World”); $response->withCookie(cookie(”name”, ”virat”, $minutes)); return $response; } public function getCookie(Request $request) { $value = $request->cookie(”name”); echo $value; } } Step 4 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get(”/cookie/set”,”CookieController@setCookie”); Route::get(”/cookie/get”,”CookieController@getCookie”); Step 5 − Visit the following URL to set the cookie. http://localhost:8000/cookie/set Step 6 − The output will appear as shown below. The window appearing in the screenshot is taken from firefox but depending on your browser, cookie can also be checked from the cookie option. Step 7 − Visit the following URL to get the cookie from the above URL. http://localhost:8000/cookie/get Step 8 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;
Category: laravel
Laravel – Hashing
Laravel – Hashing ”; Previous Next Hashing is the process of transforming a string of characters into a shorter fixed value or a key that represents the original string. Laravel uses the Hash facade which provides a secure way for storing passwords in a hashed manner. Basic Usage The following screenshot shows how to create a controller named passwordController which is used for storing and updating passwords − The following lines of code explain the functionality and usage of the passwordController − <?php namespace AppHttpControllers; use IlluminateHttpRequest; use IlluminateSupportFacadesHash; use AppHttpControllersController class passwordController extends Controller{ /** * Updating the password for the user. * * @param Request $request * @return Response */ public function update(Request $request) { // Validate the new password length… $request->user()->fill([ ”password” => Hash::make($request->newPassword) // Hashing passwords ])->save(); } } The hashed passwords are stored using make method. This method allows managing the work factor of the bcrypt hashing algorithm, which is popularly used in Laravel. Verification of Password against Hash You should verify the password against hash to check the string which was used for conversion. For this you can use the check method. This is shown in the code given below − if (Hash::check(”plain-text”, $hashedPassword)) { // The passwords match… } Note that the check method compares the plain-text with the hashedPassword variable and if the result is true, it returns a true value. Print Page Previous Next Advertisements ”;
Laravel – Understanding Release Process ”; Previous Next Every web application framework has its own version history and it is always being updated and maintained. Every latest version brings new functionality and functions which are either changed or deprecated, so it is important that you know which version will be suitable for your projects. When it comes to Laravel, there are two active versions as given below − Laravel 4- released in May 2013 Laravel 5.1- released in February 2015 Laravel 5.1 also includes various releases with the latest version of Laravel 5.1.5 which includes all the robust features for web development. The roadmap of Laravel or the version release is shown in the image below − The following points are worth notable in the context of understanding the release process of Laravel − The old directory of app/models is removed in Laravel 5.1. All the controllers, middleware and requests are grouped within a directory under the app/Http folder. A new folder namely Providers directory is replaced with the app/start files in the previous versions of Laravel 4.x. All the language files and views are moved to the resources directory. New artisan command route:cache is used for registration of new routes and is included with the release of Laravel 5.1 and further versions. Laravel supports HTTP middleware and also includes CSRF tokens and authentication model. All the authentication models are located under one directory namely resources/views/auth. It includes user registration, authentication and password controllers. Laravel Releases Version Release Bug Fixes Until Security Fixes Until V1 June 2011 – – V2 September 2011 – – v3 February 2012 – – v4 May 2013 – – 5.0 Feb 4th, 2015 Aug 4th, 2015 Feb 4th, 2016 5.1 (LTS) Jun 9th, 2015 Jun 9th, 2017 Jun 9th, 2018 5.2 Dec 21st, 2015 Jun 21st, 2016 Dec 21st, 2016 5.3 Aug 23rd, 2016 Feb 23rd, 2017 Aug 23rd, 2017 5.4 Jan 24th, 2017 Jul 24th, 2017 Jan 24th, 2018 5.5 (LTS) Aug 30th, 2017 Aug 30th, 2019 Aug 30th, 2020 5.6 Feb 7th, 2018 Aug 7th, 2018 Feb 7th, 2019 5.7 Sep 4, 2018 Feb 4th, 2019 Sep 4th, 2019 Note that the highlighted version marks the latest release. Print Page Previous Next Advertisements ”;
Laravel – Ajax
Laravel – Ajax ”; Previous Next Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications. Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function. json() function syntax json(string|array $data = array(), int $status = 200, array $headers = array(), int $options) Example Step 1 − Create a view file called resources/views/message.php and copy the following code in that file. <html> <head> <title>Ajax Example</title> <script src = “https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script> <script> function getMessage() { $.ajax({ type:”POST”, url:”/getmsg”, data:”_token = <?php echo csrf_token() ?>”, success:function(data) { $(“#msg”).html(data.msg); } }); } </script> </head> <body> <div id = ”msg”>This message will be replaced using Ajax. Click the button to replace the message.</div> <?php echo Form::button(”Replace Message”,[”onClick”=>”getMessage()”]); ?> </body> </html> Step 2 − Create a controller called AjaxController by executing the following command. php artisan make:controller AjaxController –plain Step 3 − After successful execution, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/AjaxController.php file. app/Http/Controllers/AjaxController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class AjaxController extends Controller { public function index() { $msg = “This is a simple message.”; return response()->json(array(”msg”=> $msg), 200); } } Step 5 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get(”ajax”,function() { return view(”message”); }); Route::post(”/getmsg”,”AjaxController@index”); Step 6 − Visit the following URL to test the Ajax functionality. http://localhost:8000/ajax Step 7 − You will be redirected to a page where you will see a message as shown in the following image. Step 8 − The output will appear as shown in the following image after clicking the button. Print Page Previous Next Advertisements ”;
Laravel – Facades
Laravel – Facades ”; Previous Next Facades provide a static interface to classes that are available in the application”s service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. How to create Facade The following are the steps to create Facade in Laravel − Step 1 − Create PHP Class File. Step 2 − Bind that class to Service Provider. Step 3 − Register that ServiceProvider to Configapp.php as providers. Step 4 − Create Class which is this class extends to lluminateSupportFacadesFacade. Step 5 − Register point 4 to Configapp.php as aliases. Facade Class Reference Laravel ships with many Facades. The following table show the in-built Facade class references − Facade Class Service Container Binding App IlluminateFoundationApplication app Artisan IlluminateContractsConsoleKernel artisan Auth IlluminateAuthAuthManager auth Auth (Instance) IlluminateAuthGuard Blade IlluminateViewCompilersBladeCompiler blade.compiler Bus IlluminateContractsBusDispatcher Cache IlluminateCacheRepository cache Config IlluminateConfigRepository config Cookie IlluminateCookieCookieJar cookie Crypt IlluminateEncryptionEncrypter encrypter DB IlluminateDatabaseDatabaseManager db DB (Instance) IlluminateDatabaseConnection Event IlluminateEventsDispatcher events File IlluminateFilesystemFilesystem files Gate IlluminateContractsAuthAccessGate Hash IlluminateContractsHashingHasher hash Input IlluminateHttpRequest request Lang IlluminateTranslationTranslator translator Log IlluminateLogWriter log Mail IlluminateMailMailer mailer Password IlluminateAuthPasswordsPasswordBroker auth.password Queue IlluminateQueueQueueManager queue Queue (Instance) IlluminateQueueQueueInterface Queue (Base Class) IlluminateQueueQueue Redirect IlluminateRoutingRedirector redirect Redis IlluminateRedisDatabase redis Request IlluminateHttpRequest request Response IlluminateContractsRoutingResponseFactory Route IlluminateRoutingRouter router Schema IlluminateDatabaseSchemaBlueprint Session IlluminateSessionSessionManager session Session (Instance) IlluminateSessionStore Storage IlluminateContractsFilesystemFactory filesystem URL IlluminateRoutingUrlGenerator url Validator IlluminateValidationFactory validator Validator (Instance) IlluminateValidationValidator View IlluminateViewFactory view View (Instance) IlluminateViewView Example Step 1 − Create a service provider called TestFacadesServiceProvider by executing the following command. php artisan make:provider TestFacadesServiceProvider Step 2 − After successful execution, you will receive the following output − Step 3 − Create a class called TestFacades.php at App/Test. App/Test/TestFacades.php <?php namespace AppTest; class TestFacades{ public function testingFacades() { echo “Testing the Facades in Laravel.”; } } ?> Step 4 − Create a Facade class called “TestFacades.php” at “App/Test/Facades”. App/Test/Facades/TestFacades.php <?php namespace appTestFacades; use IlluminateSupportFacadesFacade; class TestFacades extends Facade { protected static function getFacadeAccessor() { return ”test”; } } Step 5 − Create a Facade class called TestFacadesServiceProviders.php at App/Test/Facades. App/Providers/TestFacadesServiceProviders.php <?php namespace AppProviders; use App; use IlluminateSupportServiceProvider; class TestFacadesServiceProvider extends ServiceProvider { public function boot() { // } public function register() { App::bind(”test”,function() { return new AppTestTestFacades; }); } } Step 6 − Add a service provider in a file config/app.php as shown in the below figure. config/app.php Step 7 − Add an alias in a file config/app.php as shown in the below figure. config/app.php Step 8 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get(”/facadeex”, function() { return TestFacades::testingFacades(); }); Step 9 − Visit the following URL to test the Facade. http://localhost:8000/facadeex Step 10 − After visiting the URL, you will receive the following output − Print Page Previous Next Advertisements ”;
Laravel – Contracts
Laravel – Contracts ”; Previous Next Laravel contracts are a set of interfaces with various functionalities and core services provided by the framework. For example, IlluminateContractsQueueQueue contract uses a method which is needed for queuing jobs and IlluminateContractsMailMailer uses the method for sending emails. Every contract defined includes corresponding implementation of the framework. All the Laravel contracts are available in the GitHub repository as mentioned below − https://github.com/illuminate/contracts This repository provides a variety of contracts available in the Laravel framework which can be downloaded and used accordingly. Important Points While working with Laravel contracts, please note the following important points − It is mandatory to define facades in the constructor of a class. Contracts are explicitly defined in the classes and you need not define the contracts in constructors. Example Consider the contract used for Authorization in Laravel which is mentioned below − <?php namespace IlluminateContractsAuthAccess; interface Authorizable{ /** * Determine if the entity has a given ability. * * @param string $ability * @param array|mixed $arguments * @return bool */ public function can($ability, $arguments = []); } The contract uses a function can which includes a parameter named ability and arguments which uses the user identification in the form of an array. You will have to define a contract as shown in the syntax below − interface <contract-name> Contracts are used like facades for creating robust, well-tested Laravel applications. There are various practical differences with usage of contracts and facades. The following code shows using a contract for caching a repository − <?php namespace AppOrders; use IlluminateContractsCacheRepository as Cache; class Repository{ /** * The cache instance. */ protected $cache; /** * Create a new repository instance. * * @param Cache $cache * @return void */ public function __construct(Cache $cache) { $this->cache = $cache; } } Contract contains no implementation and new dependencies; it is easy to write an alternative implementation of a specified contract, thus a user can replace cache implementation without modifying any code base. Print Page Previous Next Advertisements ”;
Laravel – Sending Email
Laravel – Sending Email ”; Previous Next Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates. The following table shows the syntax and attributes of send function − Syntax void send(string|array $view, array $data, Closure|string $callback) Parameters $view(string|array) − name of the view that contains email message $data(array) − array of data to pass to view $callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message Returns nothing Description Sends email. In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below. $message → subject(”Welcome to the Tutorials Point”); $message → from(”[email protected]”, ”Mr. Example”); $message → to(”[email protected]”, ”Mr. Example”); Some of the less common methods include − $message → sender(”[email protected]”, ”Mr. Example”); $message → returnPath(”[email protected]”); $message → cc(”[email protected]”, ”Mr. Example”); $message → bcc(”[email protected]”, ”Mr. Example”); $message → replyTo(”[email protected]”, ”Mr. Example”); $message → priority(2); To attach or embed files, you can use the following methods − $message → attach(”path/to/attachment.txt”); $message → embed(”path/to/attachment.jpg”); Mail can be sent as HTML or text. You can indicate the type of mail that you want to send in the first argument by passing an array as shown below. The default type is HTML. If you want to send plain text mail then use the following syntax. Syntax Mail::send([‘text’=>’text.view’], $data, $callback); In this syntax, the first argument takes an array. Use text as the key name of the view as value of the key. Example Step 1 − We will now send an email from Gmail account and for that you need to configure your Gmail account in Laravel environment file – .env file. Enable 2-step verification in your Gmail account and create an application specific password followed by changing the .env parameters as shown below. .env MAIL_DRIVER = smtp MAIL_HOST = smtp.gmail.com MAIL_PORT = 587 MAIL_USERNAME = your-gmail-username MAIL_PASSWORD = your-application-specific-password MAIL_ENCRYPTION = tls Step 2 − After changing the .env file execute the below two commands to clear the cache and restart the Laravel server. php artisan config:cache Step 3 − Create a controller called MailController by executing the following command. php artisan make:controller MailController –plain Step 4 − After successful execution, you will receive the following output − Step 5 − Copy the following code in app/Http/Controllers/MailController.php file. app/Http/Controllers/MailController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use Mail; use AppHttpRequests; use AppHttpControllersController; class MailController extends Controller { public function basic_email() { $data = array(”name”=>”Virat Gandhi”); Mail::send([”text”=>”mail”], $data, function($message) { $message->to(”[email protected]”, ”Tutorials Point”)->subject (”Laravel Basic Testing Mail”); $message->from(”[email protected]”,”Virat Gandhi”); }); echo “Basic Email Sent. Check your inbox.”; } public function html_email() { $data = array(”name”=>”Virat Gandhi”); Mail::send(”mail”, $data, function($message) { $message->to(”[email protected]”, ”Tutorials Point”)->subject (”Laravel HTML Testing Mail”); $message->from(”[email protected]”,”Virat Gandhi”); }); echo “HTML Email Sent. Check your inbox.”; } public function attachment_email() { $data = array(”name”=>”Virat Gandhi”); Mail::send(”mail”, $data, function($message) { $message->to(”[email protected]”, ”Tutorials Point”)->subject (”Laravel Testing Mail with Attachment”); $message->attach(”C:laravel-masterlaravelpublicuploadsimage.png”); $message->attach(”C:laravel-masterlaravelpublicuploadstest.txt”); $message->from(”[email protected]”,”Virat Gandhi”); }); echo “Email Sent with attachment. Check your inbox.”; } } Step 6 − Copy the following code in resources/views/mail.blade.php file. resources/views/mail.blade.php <h1>Hi, {{ $name }}</h1> l<p>Sending Mail from Laravel.</p> Step 7 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get(”sendbasicemail”,”MailController@basic_email”); Route::get(”sendhtmlemail”,”MailController@html_email”); Route::get(”sendattachmentemail”,”MailController@attachment_email”); Step 8 − Visit the following URL to test basic email. http://localhost:8000/sendbasicemail Step 9 − The output screen will look something like this. Check your inbox to see the basic email output. Step 10 − Visit the following URL to test the HTML email. http://localhost:8000/sendhtmlemail Step 11 − The output screen will look something like this. Check your inbox to see the html email output. Step 12 − Visit the following URL to test the HTML email with attachment. http://localhost:8000/sendattachmentemail Step 13 − You can see the following output Note − In the MailController.php file the email address in the from method should be the email address from which you can send email address. Generally, it should be the email address configured on your server. Print Page Previous Next Advertisements ”;
Laravel – File Uploading
Laravel – File Uploading ”; Previous Next Uploading Files in Laravel is very easy. All we need to do is to create a view file where a user can select a file to be uploaded and a controller where uploaded files will be processed. In a view file, we need to generate a file input by adding the following line of code. Form::file(”file_name”); In Form::open(), we need to add ‘files’=>’true’ as shown below. This facilitates the form to be uploaded in multiple parts. Form::open(array(”url” => ”/uploadfile”,”files”=>”true”)); Example Step 1 − Create a view file called resources/views/uploadfile.php and copy the following code in that file. resources/views/uploadfile.php <html> <body> <?php echo Form::open(array(”url” => ”/uploadfile”,”files”=>”true”)); echo ”Select the file to upload.”; echo Form::file(”image”); echo Form::submit(”Upload File”); echo Form::close(); ?> </body> </html> Step 2 − Create a controller called UploadFileController by executing the following command. php artisan make:controller UploadFileController –plain Step 3 − After successful execution, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/UploadFileController.php file. app/Http/Controllers/UploadFileController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class UploadFileController extends Controller { public function index() { return view(”uploadfile”); } public function showUploadFile(Request $request) { $file = $request->file(”image”); //Display File Name echo ”File Name: ”.$file->getClientOriginalName(); echo ”<br>”; //Display File Extension echo ”File Extension: ”.$file->getClientOriginalExtension(); echo ”<br>”; //Display File Real Path echo ”File Real Path: ”.$file->getRealPath(); echo ”<br>”; //Display File Size echo ”File Size: ”.$file->getSize(); echo ”<br>”; //Display File Mime Type echo ”File Mime Type: ”.$file->getMimeType(); //Move Uploaded File $destinationPath = ”uploads”; $file->move($destinationPath,$file->getClientOriginalName()); } } Step 5 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get(”/uploadfile”,”UploadFileController@index”); Route::post(”/uploadfile”,”UploadFileController@showUploadFile”); Step 6 − Visit the following URL to test the upload file functionality. http://localhost:8000/uploadfile Step 7 − You will receive a prompt as shown in the following image. Print Page Previous Next Advertisements ”;
Laravel – CSRF Protection
Laravel – CSRF Protection ”; Previous Next CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized activities which the authenticated users of the system perform. As such, many web applications are prone to these attacks. Laravel offers CSRF protection in the following way − Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These tokens verify that the operations or requests are sent by the concerned authenticated user. Implementation The implementation of CSRF protection in Laravel is discussed in detail in this section. The following points are notable before proceeding further on CSRF protection − CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below − <form method = “POST” action=”/profile”> {{ csrf_field() }} … </form> You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request. The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library. Form without CSRF token Consider the following lines of code. They show a form which takes two parameters as input: email and message. <form> <label> Email </label> <input type = “text” name = “email”/> <br/> <label> Message </label> <input type=”text” name = “message”/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form> The result of the above code is the form shown below which the end user can view − The form shown above will accept any input information from an authorized user. This may make the web application prone to various attacks. Please note that the submit button includes functionality in the controller section. The postContact function is used in controllers for that associated views. It is shown below − public function postContact(Request $request) { return $request-> all(); } Observe that the form does not include any CSRF tokens so the sensitive information shared as input parameters are prone to various attacks. Form with CSRF token The following lines of code shows you the form re-designed using CSRF tokens − <form method = ”post” > {{ csrf_field() }} <label> Email </label> <input type = “text” name = “email”/> <br/> <label> Message </label> <input type = “text” name = “message”/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form> The output achieved will return JSON with a token as given below − { “token”: “ghfleifxDSUYEW9WE67877CXNVFJKL”, “name”: “TutorialsPoint”, “email”: “[email protected]” } This is the CSRF token created on clicking the submit button. Print Page Previous Next Advertisements ”;
Laravel – Authentication
Laravel – Authentication ”; Previous Next Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated. Command Laravel uses the following command to create forms and the associated controllers to perform authentication − php artisan make:auth This command helps in creating authentication scaffolding successfully, as shown in the following screenshot − Controller The controller which is used for the authentication process is HomeController. <?php namespace AppHttpControllers; use AppHttpRequests; use IlluminateHttpRequest; class HomeController extends Controller{ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware(”auth”); } /** * Show the application dashboard. * * @return IlluminateHttpResponse */ public function index() { return view(”home”); } } As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below − Login Registration Manually Authenticating Users Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password. Consider the following lines of code for LoginController which includes all the functions for authentication − <?php // Authentication mechanism namespace AppHttpControllers; use IlluminateSupportFacadesAuth; class LoginController extends Controller{ /** * Handling authentication request * * @return Response */ public function authenticate() { if (Auth::attempt([”email” => $email, ”password” => $password])) { // Authentication passed… return redirect()->intended(”dashboard”); } } } Print Page Previous Next Advertisements ”;