One place for hosting & domains

      Sharing Data Between Views Using Laravel View Composers

      Introduction

      Views hold the presentation logic of a Laravel application. It is served separately from the application logic using Laravel’s blade templating engine.

      Passing data from a controller to a view is as simple as declaring a variable and adding it as a parameter to the returned view helper method. There is no shortage of ways to do this.

      We will create a SampleController class that will handle our logic

      1. php artisan make:controller SampleController

      Here is a sample controller in app/Http/Controllers/SampleController.php

      class SampleController extends Controller
      {
          
          public function foo()
          {
              return view('foo', [
                  'key' => 'The quick brown fox jumped over the lazy dog'
              ]);
          }
      
          
          public function bar()
          {
              $key = 'If a woodchuck could chuck wood,';
      
              return view('foo', compact('key'));
          }
      
          
          public function baz()
          {
              return view('foo')->with(
                  'key',
                  'How much wood would a woodchuck chuck.'
              );
          }
      }
      

      This is all fine and dandy. Well, it is until you try passing data to many views.

      More often than not, we need to get some data on different pages. One such scenario would be information on the navigation bar or footer that will be available across all pages on your website, say, the most recent movie in theatres.

      For this example, we will use an array of 5 movies to display the latest movie (the last item on the array) on the navigation bar.

      For this, I will use a Boostrap template to set up the navigation bar in resources/views/app.blade.php.

      <nav class="navbar navbar-inverse">
              <div class="container-fluid">
      
                  <!-- Brand and toggle get grouped for better mobile display -->
                  <div class="navbar-header">
                      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                          <span class="sr-only">Toggle navigation</span>
                          <span class="icon-bar"></span>
                          <span class="icon-bar"></span>
                          <span class="icon-bar"></span>
                      </button>
                      <a class="navbar-brand" href="/">Movie Maniac</a>
                  </div>
      
                  <!-- Collect the nav links, forms, and other content for toggling -->
                  <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                      <ul class="nav navbar-nav">
                          <li><a href="foo">Foo</a></li>
                          <li><a href="bar">Bar</a></li>
                          <li><a href="baz">Baz</a></li>
                      </ul>
      
                      <ul class="nav navbar-nav navbar-right">
                          <li><a href="#">latest movie title here</a></li>
                      </ul>
      
                  </div>
                  <!-- /.navbar-collapse -->
              </div>
              <!-- /.container-fluid -->
          </nav>
      

      Placeholder text for the latest movie on navbar

      The latest movie text on the far right will however be replaced with a title from our movie list to be created later on.

      Let’s go ahead and create our movie list on the homepage.

      Routes

      View all the routes in app/Http/routes.php

      Route::get('/', 'SampleController@index');
      
      Route::get('/foo', 'SampleController@foo');
      
      Route::get('/bar', 'SampleController@bar');
      
      Route::get('/baz', 'SampleController@baz');
      

      We are just creating four simple routes.

      Controller

      View the controller in app/Http/Controllers/SampleController.php

          
          public function index()
          {
              $movieList = [
                  'Shawshank Redemption',
                  'Forrest Gump',
                  'The Matrix',
                  'Pirates of the Carribean',
                  'Back to the Future',
              ];
      
              return view('welcome', compact('movieList'));
          }
      

      View

      See latest movie views in resources/views/welcome.blade.php

      @extends('app')
      
      @section('content')
              <h1>Latest Movies</h1>
              <ul>
              @foreach($movieList as $movie)
                  <li class="list-group-item"><h5>{{ $movie }}</h5></li>
              @endforeach
              </ul>
      @endsection
      

      It goes without saying that my idea of the latest movies is skewed, but we can overlook that for now. Here is what our homepage looks like now.

      Homepage with the list of latest movies

      Awesome! We have our movie list. And now to the business of the day.

      We will assume that Back to the future, being the last movie on our movie list, is the latest movie, and display it as such on the navigation bar.

          
          public function index()
          {
              $movieList = [
                  'Shawshank Redemption',
                  'Forrest Gump',
                  'The Matrix',
                  'Pirates of the Carribean',
                  'Back to the Future',
              ];
      
              $latestMovie = end($movieList);
      
              return view('welcome', compact('movieList', 'latestMovie'));
          }
      

      We now have Back to the future as our latest movie, and rightfully so because Back to the Future 4 was released a week from now in 1985. I cannot make this stuff up.

      Homepage with the latest movie on nav bar

      This seems to work. Well until you try navigating to other pages (Try one of foo, bar, baz) created earlier on. This will throw an error.

      Error due to missing latest movie on nav bar

      This was expected and by now you must have figured out why this happened. We declared the latest movie variable on the index method of the controller and passed it to the welcome biew.
      By extension, we made latestMovie available to the navigation bar BUT only to views/welcome.blade.php.

      When we navigate to /foo, our navigation bar still expects a latestMovie variable to be passed to it from the foo method but we have none to give.

      There are three ways to fix this

      • Declare the latestMovie value in every other method, and in this case, the movieList too. It goes without saying we will not be doing this.

      • Place the movie information in a service provider’s boot method. You can place it on App/Providers/AppServiceProvider or create one. This quickly becomes inefficient if we are sharing a lot of data.

          
          public function boot()
          {
              view()->share('key', 'value');
          }
      
      • Take advantage of Laravel View composers

      View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location.

      -Laravel documentation

      While it is possible to get the data in every controller method and pass it to the single view, this approach may be undesirable.

      View composers, as described from the Laravel documentation, bind data to a view every time it is rendered. They clean our code by getting fetching data once and passing it to the view.

      Since Laravel does not include a ViewComposers directory in its application structure, we will have to create our own for better organization. Go ahead and create App\Http\ViewComposers

      We will then proceed to create a new service provider to handle all our view composers using the artisan command

      1. php artisan make:provider ComposerServiceProvider

      The service provider will be visible in app/Providers

      Add the ComposerServiceProvider class to config/app.php array for providers so that Laravel is able to identify it.

      Modify the boot method in the new Provider by adding a composer method that extends view()

      
          public function boot()
          {
              view()->composer(
                  'app',
                  'App\Http\ViewComposers\MovieComposer'
              );
          }
      

      Laravel will execute a MovieComposer@compose method every time app.blade.php is rendered. This means that every time our navigation bar is loaded, we will be ready to serve it with the latest movie from our view composer.

      While MovieComposer@compose is the default method to be called, you can overwrite it by specifying your own custom method name in the boot method.

      view()->composer('app',  'App\Http\ViewComposers\MovieComposer@foobar');
      

      Next, we will create our MovieComposer class

      <?php
      
      namespace App\Http\ViewComposers;
      
      use Illuminate\View\View;
      
      class MovieComposer
      {
          public $movieList = [];
          
          public function __construct()
          {
              $this->movieList = [
                  'Shawshank Redemption',
                  'Forrest Gump',
                  'The Matrix',
                  'Pirates of the Carribean',
                  'Back to the Future',
              ];
          }
      
          
          public function compose(View $view)
          {
              $view->with('latestMovie', end($this->movieList));
          }
      }
      

      The with method will bind the latestMovies to the app view when it is rendered. Notice that we added Illuminate\View\View.

      We can now get rid of the latestMovie variable and actually remove it from the compact helper method in SampleController@index.

      public function index()
          {
              $movieList = [
                  'Shawshank Redemption',
                  'Forrest Gump',
                  'The Matrix',
                  'Pirates of the Carribean',
                  'Back to the Future',
              ];
      
              return view('welcome', compact('movieList'));
          }
      

      We can now access the latest movie on the navigation bar in all our routes.

      View latest movies in all routes

      While we seem to have solved one issue, we seem to have created another. we now have two movieList arrays. one in the controller and one in the constructor method in MovieComposer.

      While this may have been caused by using an array as a simple data source, it may be a good idea to fix it, say, by creating a movie repository. Ideally, the latestMovie value would be gotten from a database using Eloquent.

      Check out the GitHub repo for this tutorial to see how I created a Movie Repository to get around the redundancy as shown below in MovieComposer and SampleController.

          public $movieList = [];
      
          
          public function __construct(MovieRepository $movies)
          {
              $this->movieList = $movies->getMovieList();
          }
      
          
          public function compose(View $view)
          {
              $view->with('latestMovie', end($this->movieList));
          }
      
          public function index(MovieRepository $movies)
          {
              $movieList = $movies->getMovieList();
      
              return view('welcome', compact('movieList'));
          }
      

      It is possible to create a view composer that is executed when all views are rendered by replacing the view name with an asterisk wildcard

      view()->composer('*', function (View $view) {
          
      });
      

      Notice that instead of passing a string with the path to MovieComposer, you can also pass a closure.

      You can also limit the view composer to a finite number of views, say, nav and footer

      view()->composer(
          ['nav', 'footer'],
          'App\Http\ViewComposers\MovieComposer'
      );
      

      View Invoices and Payment History


      All of your billing history, including previous invoices and payments, is accessible within the
      Cloud Manager on the Billing & Payment History section within the Billing Info page (see
      Accessing Billing Information). By default, all transactions (both invoices and payments) from the last 6 months are displayed. To customize this, use the dropdown menus on the top right of this section.

      To view an itemized invoice, find the invoice row on the list and click the corresponding invoice number. This opens up a new page that displays each service that was active during the billing period, along with the additional details listed below:

      • Description: The type of service and the unique label you’ve given it.
      • From: The date the service started billing during this billing cycle. This could either be the date and time this billing cycle started or the date and time the service was added to the account.
      • To: The date the service ended billing during this billing cycle. This could either be the date and time this billing cycle ended or the date and time the service was removed from the account.
      • Quantity: The number of hours the service is being billed.
      • Unit Price: The hourly rate for this service.
      • Amount: The cost for this service excluding taxes.
      • Taxes: The taxes that are charged for this service.
      • Total: The cost for this service including taxes.

      Downloading Invoices (PDF and CSV)

      An invoice or payment can be downloaded as either a PDF or a CSV file. To do this, open the invoice within the Cloud Manager and select either the Download CSV or Download PDF button.

      This page was originally published on



      Source link

      How To View The Source Code of an HTML Document



      Part of the Series:
      How To Build a Website With HTML

      This tutorial series will guide you through creating and further customizing this website using HTML, the standard markup language used to display documents in a web browser. No prior coding experience is necessary but we recommend you start at the beginning of the series if you wish to recreate the demonstration website.

      At the end of this series, you should have a website ready to deploy to the cloud and a basic familiarity with HTML. Knowing how to write HTML will provide a strong foundation for learning additional front-end web development skills, such as CSS and JavaScript.

      HTML is used to mark up a document with instructions that tell a browser how to display and interpret the document’s content. For example, HTML can tell the browser which text content should be interpreted as a heading and which text content should be interpreted as paragraphs. HTML is also used to add images and assign links to text and images. These instructions are communicated through HTML tags, which are written like this: <tagname>. Many, though not all tags, use an opening tag and closing tag to wrap around the content that they are used to modify.

      To get a sense of how these tags are used, let’s inspect a snippet of HTML code. The HTML code below shows how HTML tags are used to structure text and add links and images. Don’t worry if you don’t understand the tags immediately- we’ll study those in the next tutorial.

      <h1>Sammy's Sample HTML</h1>
      
      <p>This code is an example of how HTML is written.</p>
      
      <p>It uses HTML tags to structure the text.</p>
      
      <p>It uses HTML to add a <a href="https://www.digitalocean.com/community/tutorials/digitalocean.com/community">link</a>.</p>
      
      <p>And it also uses HTML to add an image:</p>
      
      <img src="https://html.sammy-codes.com/images/small-profile.jpeg"/>
      

      This HTML code is rendered in the browser as follows:

      HTML Document

      Viewing the Source Code of a Webpage

      Nearly every webpage you come across uses HTML to structure and display HTML pages. You can inspect the source code of any webpage by using a web browser like Firefox or Chrome. On Firefox, navigate to the “Tools” menu item in the top menu and click on “Web Developer/Page Source” like so:

      Gif of how to inspect source code using Firefox

      On Firefox, you can also use the keyboard shortcut Command-U to view the source code of a webpage.

      On Chrome, the process is very similar. Navigate to the top menu item “View” and click on “Developer/View Source.” You can also use the keyboard shortcut Option-Command-U.

      Try inspecting the source code of the demo website that we will build in this tutorial series. You should receive a page with many more HTML tags than our example above. Don’t be alarmed if it seems overwhelming. By the end of this tutorial series, you should have a better understanding of how to interpret HTML source code and how to use HTML to build and customize your own websites.

      Note: As mentioned above, you can inspect the source code of any webpage using tools from the Firefox or Chrome web browser. Try inspecting the code of a few of your favorite websites to get a sense of the underlying code that structures web documents. Though the source code of these sites will likely contain more languages than HTML, learning HTML first will help prepare you to learn additional languages and frameworks for creating websites later on if you wish.

      You should now have a general understanding of the format of an HTML document and know how to inspect HTML source code using a browser tool. To better understand how HTML works, let’s inspect its key components. In the next tutorial, we will learn more about HTML elements, the building blocks that are used to create HTML documents.



      Source link