Laravel – Redirections

Laravel – Redirections ”; Previous Next Named route is used to give specific name to a route. The name can be assigned using the “as” array key. Route::get(”user/profile”, [”as” => ”profile”, function () { // }]); Note − Here, we have given the name profile to a route user/profile. Redirecting to Named Routes Example Observe the following example to understand more about Redirecting to named routes − Step 1 − Create a view called test.php and save it at resources/views/test.php. <html> <body> <h1>Example of Redirecting to Named Routes</h1> </body> </html> Step 2 − In routes.php, we have set up the route for test.php file. We have renamed it to testing. We have also set up another route redirect which will redirect the request to the named route testing. app/Http/routes.php Route::get(”/test”, [”as”=>”testing”,function() { return view(”test2”); }]); Route::get(”redirect”,function() { return redirect()->route(”testing”); }); Step 3 − Visit the following URL to test the named route example. http://localhost:8000/redirect Step 4 − After execution of the above URL, you will be redirected to http://localhost:8000/test as we are redirecting to the named route testing. Step 5 − After successful execution of the URL, you will receive the following output − Redirecting to Controller Actions Not only named route but we can also redirect to controller actions. We need to simply pass the controller and name of the action to the action method as shown in the following example. If you want to pass a parameter, you can pass it as the second argument of the action method. return redirect()->action(‘NameOfController@methodName’,[parameters]); Example Step 1 − Execute the following command to create a controller called RedirectController. php artisan make:controller RedirectController –plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code to file app/Http/Controllers/RedirectController.php. app/Http/Controllers/RedirectController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class RedirectController extends Controller { public function index() { echo “Redirecting to controller”s action.”; } } Step 4 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get(”rr”,”RedirectController@index”); Route::get(”/redirectcontroller”,function() { return redirect()->action(”RedirectController@index”); }); Step 5 − Visit the following URL to test the example. http://localhost:8000/redirectcontroller Step 6 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;

Laravel – Authorization

Laravel – Authorization ”; Previous Next In the previous chapter, we have studied about authentication process in Laravel. This chapter explains you the authorization process in Laravel. Difference between Authentication and Authorization Before proceeding further into learning about the authorization process in Laravel, let us understand the difference between authentication and authorization. In authentication, the system or the web application identifies its users through the credentials they provide. If it finds that the credentials are valid, they are authenticated, or else they are not. In authorization, the system or the web application checks if the authenticated users can access the resources that they are trying to access or make a request for. In other words, it checks their rights and permissions over the requested resources. If it finds that they can access the resources, it means that they are authorized. Thus, authentication involves checking the validity of the user credentials, and authorization involves checking the rights and permissions over the resources that an authenticated user has. Authorization Mechanism in Laravel Laravel provides a simple mechanism for authorization that contains two primary ways, namely Gates and Policies. Writing Gates and Policies Gates are used to determine if a user is authorized to perform a specified action. They are typically defined in App/Providers/AuthServiceProvider.php using Gate facade. Gates are also functions which are declared for performing authorization mechanism. Policies are declared within an array and are used within classes and methods which use authorization mechanism. The following lines of code explain you how to use Gates and Policies for authorizing a user in a Laravel web application. Note that in this example, the boot function is used for authorizing the users. <?php namespace AppProviders; use IlluminateContractsAuthAccessGate as GateContract; use IlluminateFoundationSupportProvidersAuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider{ /** * The policy mappings for the application. * * @var array */ protected $policies = [ ”AppModel” => ”AppPoliciesModelPolicy”, ]; /** * Register any application authentication / authorization services. * * @param IlluminateContractsAuthAccessGate $gate * @return void */ public function boot(GateContract $gate) { $this->registerPolicies($gate); // } } Print Page Previous Next Advertisements ”;

Laravel – Response

Laravel – Response ”; Previous Next A web application responds to a user’s request in many ways depending on many parameters. This chapter explains you in detail about responses in Laravel web applications. Basic Response Laravel provides several different ways to return response. Response can be sent either from route or from controller. The basic response that can be sent is simple string as shown in the below sample code. This string will be automatically converted to appropriate HTTP response. Example Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get(”/basic_response”, function () { return ”Hello World”; }); Step 2 − Visit the following URL to test the basic response. http://localhost:8000/basic_response Step 3 − The output will appear as shown in the following image. Attaching Headers The response can be attached to headers using the header() method. We can also attach the series of headers as shown in the below sample code. return response($content,$status) ->header(”Content-Type”, $type) ->header(”X-Header-One”, ”Header Value”) ->header(”X-Header-Two”, ”Header Value”); Example Observe the following example to understand more about Response − Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get(”/header”,function() { return response(“Hello”, 200)->header(”Content-Type”, ”text/html”); }); Step 2 − Visit the following URL to test the basic response. http://localhost:8000/header Step 3 − The output will appear as shown in the following image. Attaching Cookies The withcookie() helper method is used to attach cookies. The cookie generated with this method can be attached by calling withcookie() method with response instance. By default, all cookies generated by Laravel are encrypted and signed so that they can”t be modified or read by the client. Example Observe the following example to understand more about attaching cookies − Step 1 − Add the following code to app/Http/routes.php file. app/Http/routes.php Route::get(”/cookie”,function() { return response(“Hello”, 200)->header(”Content-Type”, ”text/html”) ->withcookie(”name”,”Virat Gandhi”); }); Step 2 − Visit the following URL to test the basic response. http://localhost:8000/cookie Step 3 − The output will appear as shown in the following image. JSON Response JSON response can be sent using the json method. This method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response. Example Observe the following example to understand more about JSON Response − Step 1 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get(”json”,function() { return response()->json([”name” => ”Virat Gandhi”, ”state” => ”Gujarat”]); }); Step 2 − Visit the following URL to test the json response. http://localhost:8000/json Step 3 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;

Laravel – Blade Templates

Laravel – Blade Templates ”; Previous Next Laravel 5.1 introduces the concept of using Blade, a templating engine to design a unique layout. The layout thus designed can be used by other views, and includes a consistent design and structure. When compared to other templating engines, Blade is unique in the following ways − It does not restrict the developer from using plain PHP code in views. The blade views thus designed, are compiled and cached until they are modified. The complete directory structure of Laravel is shown in the screenshot given here. You can observe that all views are stored in the resources/views directory and the default view for Laravel framework is welcome.blade.php. Please note that other blade templates are also created similarly. Steps for Creating a Blade Template Layout You will have to use the following steps to create a blade template layout − Step 1 Create a layout folder inside the resources/views folder. We are going to use this folder to store all layouts together. Create a file name master.blade.php which will have the following code associated with it − <html> <head> <title>DemoLaravel – @yield(”title”)</title> </head> <body> @yield(”content”) </body> </html> Step 2 In this step, you should extend the layout. Extending a layout involves defining the child elements. Laravel uses the Blade @extends directive for defining the child elements. When you are extending a layout, please note the following points − Views defined in the Blade Layout injects the container in a unique way. Various sections of view are created as child elements. Child elements are stored in layouts folder as child.blade.php An example that shows extending the layout created above is shown here − @extends(”layouts.app”) @section(”title”, ”Page Title”) @section(”sidebar”) @parent <p>This refers to the master sidebar.</p> @endsection @section(”content”) <p>This is my body content.</p> @endsection Step 3 To implement the child elements in views, you should define the layout in the way it is needed. Observe the screenshot shown here. You can find that each of links mentioned in the landing page are hyperlinks. Please note that you can also create them as child elements with the help of blade templates by using the procedure given above. Print Page Previous Next Advertisements ”;

Laravel – Error Handling

Laravel – Error Handling ”; Previous Next Most web applications have specific mechanisms for error handling. Using these, they track errors and exceptions, and log them to analyze the performance. In this chapter, you will read about error handling in Laravel applications. Important Points Before proceeding further to learn in detail about error handling in Laravel, please note the following important points − For any new project, Laravel logs errors and exceptions in the AppExceptionsHandler class, by default. They are then submitted back to the user for analysis. When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application. By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces. The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file. The value is set to true in a local development environment and is set to false in a production environment. If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher. Error Log Logging the errors in a web application helps to track them and in planning a strategy for removing them. The log information can be configured in the web application in config/app.php file. Please note the following points while dealing with Error Log in Laravel − Laravel uses monolog PHP logging library. The logging parameters used for error tracking are single, daily, syslog and errorlog. For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below − ”log” => env(”APP_LOG”,’daily’), If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value. ‘log_max_files’ => 25; Severity Levels As Laravel uses monolog PHP logging library, there are various parameters used for analyzing severity levels. Various severity levels that are available are error, critical, alert and emergency messages. You can set the severity level as shown in the command below − ”log_level” => env(”APP_LOG_LEVEL”, ”error”) Print Page Previous Next Advertisements ”;

Laravel – Working With Database

Laravel – Working With Database ”; Previous Next Laravel has made processing with database very easy. Laravel currently supports following 4 databases − MySQL Postgres SQLite SQL Server The query to the database can be fired using raw SQL, the fluent query builder, and the Eloquent ORM. To understand the all CRUD (Create, Read, Update, Delete) operations with Laravel, we will use simple student management system. Connecting to Database Configure the database in config/database.php file and create the college database with structure in MySQL as shown in the following table. Database: College Table: student Column Name Column Datatype Extra Id int(11) Primary key | Auto increment Name varchar(25) We will see how to add, delete, update and retrieve records from database using Laravel in student table. Sr.No. Record & Description 1 Insert Records We can insert the record using the DB facade with insert method. 2 Retrieve Records After configuring the database, we can retrieve the records using the DB facade with select method. 3 Update Records We can update the records using the DB facade with update method. 4 Delete Records We can delete the record using the DB facade with the delete method. Print Page Previous Next Advertisements ”;

Laravel – Session

Laravel – Session ”; Previous Next Sessions are used to store information about the user across the requests. Laravel provides various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used because it is lightweight. Session can be configured in the file stored at config/session.php. Accessing Session Data To access the session data, we need an instance of session which can be accessed via HTTP request. After getting the instance, we can use the get() method, which will take one argument, “key”, to get the session data. $value = $request->session()->get(”key”); You can use all() method to get all session data instead of get() method. Storing Session Data Data can be stored in session using the put() method. The put() method will take two arguments, the “key” and the “value”. $request->session()->put(”key”, ”value”); Deleting Session Data The forget() method is used to delete an item from the session. This method will take “key” as the argument. $request->session()->forget(”key”); Use flush() method instead of forget() method to delete all session data. Use the pull() method to retrieve data from session and delete it afterwards. The pull() method will also take key as the argument. The difference between the forget() and the pull() method is that forget() method will not return the value of the session and pull() method will return it and delete that value from session. Example Step 1 − Create a controller called SessionController by executing the following command. php artisan make:controller SessionController –plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in a file at app/Http/Controllers/SessionController.php. app/Http/Controllers/SessionController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class SessionController extends Controller { public function accessSessionData(Request $request) { if($request->session()->has(”my_name”)) echo $request->session()->get(”my_name”); else echo ”No data in the session”; } public function storeSessionData(Request $request) { $request->session()->put(”my_name”,”Virat Gandhi”); echo “Data has been added to session”; } public function deleteSessionData(Request $request) { $request->session()->forget(”my_name”); echo “Data has been removed from session.”; } } Step 4 − Add the following lines at app/Http/routes.php file. app/Http/routes.php Route::get(”session/get”,”SessionController@accessSessionData”); Route::get(”session/set”,”SessionController@storeSessionData”); Route::get(”session/remove”,”SessionController@deleteSessionData”); Step 5 − Visit the following URL to set data in session. http://localhost:8000/session/set Step 6 − The output will appear as shown in the following image. Step 7 − Visit the following URL to get data from session. http://localhost:8000/session/get Step 8 − The output will appear as shown in the following image. Step 9 − Visit the following URL to remove session data. http://localhost:8000/session/remove Step 10 − You will see a message as shown in the following image. Print Page Previous Next Advertisements ”;

Laravel – Localization

Laravel – Localization ”; Previous Next Localization feature of Laravel supports different language to be used in application. You need to store all the strings of different language in a file and these files are stored at resources/views directory. You should create a separate directory for each supported language. All the language files should return an array of keyed strings as shown below. <?php return [ ”welcome” => ”Welcome to the application” ]; Example Step 1 − Create 3 files for languages − English, French, and German. Save English file at resources/lang/en/lang.php <?php return [ ”msg” => ”Laravel Internationalization example.” ]; ?> Step 2 − Save French file at resources/lang/fr/lang.php. <?php return [ ”msg” => ”Exemple Laravel internationalisation.” ]; ?> Step 3 − Save German file at resources/lang/de/lang.php. <?php return [ ”msg” => ”Laravel Internationalisierung Beispiel.” ]; ?> Step 4 − Create a controller called LocalizationController by executing the following command. php artisan make:controller LocalizationController –plain Step 5 − After successful execution, you will receive the following output − Step 6 − Copy the following code to file app/Http/Controllers/LocalizationController.php app/Http/Controllers/LocalizationController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class LocalizationController extends Controller { public function index(Request $request,$locale) { //set’s application’s locale app()->setLocale($locale); //Gets the translated message and displays it echo trans(”lang.msg”); } } Step 7 − Add a route for LocalizationController in app/Http/routes.php file. Notice that we are passing {locale} argument after localization/ which we will use to see output in different language. app/Http/routes.php Route::get(”localization/{locale}”,”LocalizationController@index”); Step 8 − Now, let us visit the different URLs to see all different languages. Execute the below URL to see output in English language. http://localhost:8000/localization/en Step 9 − The output will appear as shown in the following image. Step 10 − Execute the below URL to see output in French language. http://localhost:8000/localization/fr Step 11 − The output will appear as shown in the following image. Step 12 − Execute the below URL to see output in German language http://localhost:8000/localization/de Step 13 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;

Laravel – Views

Laravel – Views ”; Previous Next In MVC framework, the letter “V” stands for Views. It separates the application logic and the presentation logic. Views are stored in resources/views directory. Generally, the view contains the HTML which will be served by the application. Example Observe the following example to understand more about Views − Step 1 − Copy the following code and save it at resources/views/test.php <html> <body> <h1>Hello, World</h1> </body> </html> Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view. app/Http/routes.php Route::get(”/test”, function() { return view(”test”); }); Step 3 − Visit the following URL to see the output of the view. http://localhost:8000/test Step 4 − The output will appear as shown in the following image. Passing Data to Views While building application it may be required to pass data to the views. Pass an array to view helper function. After passing an array, we can use the key to get the value of that key in the HTML file. Example Observe the following example to understand more about passing data to views − Step 1 − Copy the following code and save it at resources/views/test.php <html> <body> <h1><?php echo $name; ?></h1> </body> </html> Step 2 − Add the following line in app/Http/routes.php file to set the route for the above view. app/Http/routes.php Route::get(”/test”, function() { return view(”test”,[‘name’=>’Virat Gandhi’]); }); Step 3 − The value of the key name will be passed to test.php file and $name will be replaced by that value. Step 4 − Visit the following URL to see the output of the view. http://localhost:8000/test Step 5 − The output will appear as shown in the following image. Sharing Data with all Views We have seen how we can pass data to views but at times, there is a need to pass data to all the views. Laravel makes this simpler. There is a method called share() which can be used for this purpose. The share() method will take two arguments, key and value. Typically share() method can be called from boot method of service provider. We can use any service provider, AppServiceProvider or our own service provider. Example Observe the following example to understand more about sharing data with all views − Step 1 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get(”/test”, function() { return view(”test”); }); Route::get(”/test2”, function() { return view(”test2”); }); Step 2 − Create two view files — test.php and test2.php with the same code. These are the two files which will share data. Copy the following code in both the files. resources/views/test.php & resources/views/test2.php <html> <body> <h1><?php echo $name; ?></h1> </body> </html> Step 3 − Change the code of boot method in the file app/Providers/AppServiceProvider.php as shown below. (Here, we have used share method and the data that we have passed will be shared with all the views.) app/Providers/AppServiceProvider.php <?php namespace AppProviders; use IlluminateSupportServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { view()->share(”name”, ”Virat Gandhi”); } /** * Register any application services. * * @return void */ public function register() { // } } Step 4 − Visit the following URLs. http://localhost:8000/test http://localhost:8000/test2 Step 5 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;

Laravel – Request

Laravel – Request ”; Previous Next In this chapter, you will learn in detail about Requests in Laravel. Retrieving the Request URI The “path” method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which matches the particular pattern specified in the argument of the method. To get the full URL, we can use the url method. Example Step 1 − Execute the below command to create a new controller called UriController. php artisan make:controller UriController –plain Step 2 − After successful execution of the URL, you will receive the following output − Step 3 − After creating a controller, add the following code in that file. app/Http/Controllers/UriController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class UriController extends Controller { public function index(Request $request) { // Usage of path method $path = $request->path(); echo ”Path Method: ”.$path; echo ”<br>”; // Usage of is method $pattern = $request->is(”foo/*”); echo ”is Method: ”.$pattern; echo ”<br>”; // Usage of url method $url = $request->url(); echo ”URL method: ”.$url; } } Step 4 − Add the following line in the app/Http/route.php file. app/Http/route.php Route::get(”/foo/bar”,”UriController@index”); Step 5 − Visit the following URL. http://localhost:8000/foo/bar Step 6 − The output will appear as shown in the following image. Retrieving Input The input values can be easily retrieved in Laravel. No matter what method was used “get” or “post”, the Laravel method will retrieve input values for both the methods the same way. There are two ways we can retrieve the input values. Using the input() method Using the properties of Request instance Using the input() method The input() method takes one argument, the name of the field in form. For example, if the form contains username field then we can access it by the following way. $name = $request->input(”username”); Using the properties of Request instance Like the input() method, we can get the username property directly from the request instance. $request->username Example Observe the following example to understand more about Requests − Step 1 − Create a Registration form, where user can register himself and store the form at resources/views/register.php <html> <head> <title>Form Example</title> </head> <body> <form action = “/user/register” method = “post”> <input type = “hidden” name = “_token” value = “<?php echo csrf_token() ?>”> <table> <tr> <td>Name</td> <td><input type = “text” name = “name” /></td> </tr> <tr> <td>Username</td> <td><input type = “text” name = “username” /></td> </tr> <tr> <td>Password</td> <td><input type = “text” name = “password” /></td> </tr> <tr> <td colspan = “2” align = “center”> <input type = “submit” value = “Register” /> </td> </tr> </table> </form> </body> </html> Step 2 − Execute the below command to create a UserRegistration controller. php artisan make:controller UserRegistration –plain Step 3 − After successful execution of the above step, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/UserRegistration.php controller. app/Http/Controllers/UserRegistration.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class UserRegistration extends Controller { public function postRegister(Request $request) { //Retrieve the name input field $name = $request->input(”name”); echo ”Name: ”.$name; echo ”<br>”; //Retrieve the username input field $username = $request->username; echo ”Username: ”.$username; echo ”<br>”; //Retrieve the password input field $password = $request->password; echo ”Password: ”.$password; } } Step 5 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get(”/register”,function() { return view(”register”); }); Route::post(”/user/register”,array(”uses”=>”UserRegistration@postRegister”)); Step 6 − Visit the following URL and you will see the registration form as shown in the below figure. Type the registration details and click Register and you will see on the second page that we have retrieved and displayed the user registration details. http://localhost:8000/register Step 7 − The output will look something like as shown in below the following images. Print Page Previous Next Advertisements ”;