- This topic has 0 replies, 1 voice, and was last updated 1 year ago by
Chinomnso.
- AuthorPosts
- December 19, 2019 at 1:48 am #82417Participant@chinomnso
I’ve written about views in the past, and I mentioned that views hold the markup for your website. They do not hold logic. Rather, they just present data that has been prepared by the controller. The challenge now is how to pass data from a controller to a view. Let us see how we can do that in this article.
If you want to get up to speed with basic Laravel concepts, you may wish to read up my beginner article on installing Laravel on your local machine. Then you can learn about controllers and views. You may also want to brush up on routes as we would also be working with them a lot. Believing you are ready, let’s go right in.
A Little About Controllers
Let’s build as we go, and see how much we can learn along the way. Let’s create a controller for the static pages on your website – Home, About Me and Contact Me. To create a controller, navigate to App/Http/Controllers/. Righ-click on the Controllers/ folder and create a new file. Name it “PagesController.php”. In the file, type the following code, or just copy and paste it:
1234567891011121314151617<?phpnamespace App\Http\Controllers;class PagesController {public function getHome(){//function logic goes here}public function getAbout(){//function logic goes here}public function getContact(){//function logic goes here}}Note in the code above, each of the function names is preceded by "get." This is one of the several HTTP verbs or methods. The most common of them are GET, POST, PUT, PATCH and DELETE. It's not a must that you would name your functions after these HTTP verbs, but it can be helpful when you're looking at your code - you would easily be able to spot what a function is doing in your code, or at least have an idea of the kind of task it carries out. So, we have just created a controller that handles the static pages on your site: Home, About and Contact.
Based on the code samples in my previous article on routes and routing, the routes for the pages above would look something like the following:
1234567891011Route::get('/', function(){return view('home');});Route::get('about', function(){return view('about');});Route::get('contact', function(){return view('contact');});Writing our code like this would make us have functions in our routes. It's not so cool having functions inside routes. We want to keep our code as organized and as simple as possible. Let us now change our code to something more organized and effect changes in our views. For the code to work we must have created all the corresponding page layouts in the resources/views directory: home.blade.php, about.blade.php and contact.blade.php.
To follow along, simply copy the code from the welcome.blade.php file and paste it in each of the files you've just created. Then, make a few changes to the content so you'll have something unique to each of the views. Load each of the pages in the browser and you should see your pages working. Your homepage would look something like this:
Now, let us sanitize the web.php file containing our routes and make it look a lot simpler. We will transfer some of the code there to the PagesController.php file. Here's how our new PagesController.php file should look now:
1234567891011121314151617<?phpnamespace App\HTTP\Controllers;class StaticController {public function getHome(){return view('home');}public function getAbout(){return view('about');}public function getContact(){return view('contact');}}I'm sure you noticed the new return construct there. Initially, this was in the web.php file. But in order to take out functions from that file, we have moved it here. But this would not work on its own. We need to make adjustments to our routes in the web.php file. Copy and paste the code below in the web.php file in the routes/ directory.
12345678910111213<?php/*|--------------------------------------------------------------------------| Web Routes|--------------------------------------------------------------------------*/Route::get('/', 'StaticController@getHome');Route::get('about', 'StaticController@getAbout');Route::get('contact', 'StaticController@getContact');In our new file, we have multiple functions for rendering different views. Therefore, in our web.php file, we need to point the routes to the individual functions handling each of the views that have been specified in the controller file. Notice that the name of the controller is referenced in the route and the particular method to be used is called using @.
Passing Data To A View
What we want to do now is to demonstrate or simulate logic in our controller. What we will be doing is going to be very basic. In the real world, you would most likely not be doing something as basic as this. But at least, it will give you an idea of how this whole thing works. We would create an array and some variables, then we would pass these to a view.
We will work with the About view. But first, let us add some code to the
getAbout()
function.12345678public function getAbout(){$fname = "John";$lname = "Doe";$yob = 1990;$currYear = date("Y");$age = $currYear - $yob;return view('about');}I've added a number of variables to the method above. But for a view to render the data held in those variables, you need to make the data available to the view. In simple terms, it's like you're informing the view that there's some data coming along from the controller. You must explicitly pass them to the view. To do that, take note of the differences betwen the previous code snippet and the next:
123456789public function getAbout(){$fname = "John";$lname = "Doe";$yob = 1990;$currYear = date("Y");$age = $currYear - $yob;return view('about')->with("fname", $fname);}Did you notice the last line of code in the
getAbout()
method? There is something new there: a new method,with("fname", $fname)
was introduced. That is the method used to pass data to a view. Note that the first argument is the exact name of the variable that follows, except for the dollar sign.You can also pass multiple bits of data to a view. You can even pass arrays. Let us add an array to what we already have, then let us try displaying the contents of the array to the view, along with other bits of data. The purpose is to prepare you for bigger things you will encounter later in this series of building a blog with Laravel. For example, when you will be displaying a blog post, you will be displaying information like the title, date it was posted, category or categories, the body, and comments if any. Change the previous block of code to the one that follows.
1234567891011public function getAbout(){$fname = "John";$lname = "Doe";$yob = 1990;$currYear = date("Y");$age = $currYear - $yob;$personalInfo = [];$personalInfo['work'] = "write code";$personalInfo['hobby'] = "play the guitar";return view('about')->with("fname", $fname)->with("lname", $lname)->with("personalInfo", $personalInfo);}I'm sure you noticed how multiple bits of data were added to the method and passed to the view. Now, let us head over to the view and "receive" these things that have been passed over to it. Head over to the about.blade.php file in the directory containing your views and add the following code:
12345<div class="title m-b-md">{{ $fname }} {{ $lname }}</div>I {{ $personalInfo['work'] }} for a living, and when I'm not coding, I {{ $personalInfo['hobby'] }} for fun.Take note of how the variable
$fname
was called in the template - it is enclosed in pairs of curly braces. And for the array, you call the particular item by its index. If it is a numerically indexed array, then you would have to access it by means of the numeric index.If you carefully followed everything I've done here, you should not have any problems. Simply head over to the appropriate page and reload your browser. You should see the view properly rendered, with the right data in it. You should see something like this:
This is just the first in a series of posts to teach you how to create a blog with Laravel. It's not as hard as you think. Just follow the steps carefully and you will be fine. If you have any questions or don't understand anything here, just drop your questions in the replies. I will gladly answer your questions.
- AuthorPosts
- You must be logged in to reply to this topic.