Javatpoint Logo
Javatpoint Logo

Passing data to views

In this topic, we will learn that how we can pass the data to views.

There are various ways of passing data to views:

  • By using the name array
  • By using with() function
  • By using compact() function

Name array

The name array is the array of data that is passed as the second parameter to the view() method.

Let's understand through an example.

Step 1: First, we create the student.blade.php, which contains the view of the page.

student.blade.php

In the above code, we are displaying the values of three variables, i.e., name1, name2, and name3. The values of these three are retrieved from the StudentController.php file.

Step 2: Now, we create the StudentController.php file.

StudentController.php.

In the above code, we have defined the display() function in which we are returning the view of the student.blade.php file.

Step 3: Now, we define the route in web.php file.

web.php

Output

Laravel Passing data to views

with() function

We can also use the with() function to pass the data to views.

  • First, we create the student.blade.php file which contains the view of the page.

The above code displays the value of the 'id'.

  • Now, we create the StudentController.php file.

In the above code, we create the display() function that returns the view of the student.blade.php file, and we are passing the value of 'id' by using the with() function. The 'with()' function contains two parameters, i.e., variable name(id) and the value of the 'id'.

  • Now, we define the route.

Output

Laravel Passing data to views

compact() function

The compact() function is also used to pass the data to views. It contains a single parameter, i.e., the name of the variable.

Let's understand through an example.

  • First, we create the student.blade.php file which contains the view of the page.
  • Now, we create the StudentController.php file.
  • Now, we define the route in the web.php file.

Output

Laravel Passing data to views

We can pass multiple parameters to the compact() function.

Let's understand through an example.

Student.blade.php

StudentController.php

web.php

Output

Laravel Passing data to views




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA