个性化阅读
专注于IT技术分析

Laravel将数据传递到视图

本文概述

在本主题中, 我们将学习如何将数据传递给视图。

有多种将数据传递到视图的方法:

  • 通过使用名称数组
  • 通过使用with()函数
  • 通过使用compact()函数

名称数组

名称数组是作为第二个参数传递给view()方法的数据数组。

让我们通过一个例子来理解。

步骤1:首先, 我们创建了student.blade.php, 其中包含页面视图。

student.blade.php

<html>
 <body>
 <h1>Name of the Students are : <br>
 <?php 
echo $name1;
echo "<br>";
echo $name2;
echo "<br>";
echo $name3; ?></h1>
</body>
</html>

在上面的代码中, 我们显示了三个变量的值, 即name1, name2和name3。这三个值是从StudentController.php文件中检索的。

步骤2:现在, 我们创建StudentController.php文件。

StudentController.php。

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StudentController extends Controller
{
   public function display()
  {
     return view('student', ['name1'=> 'Anisha', 'name2'=>'Nishka', 'name3'=>'Sumit']);
  } 
  }

在上面的代码中, 我们定义了display()函数, 在该函数中返回student.blade.php文件的视图。

步骤3:现在, 我们在web.php文件中定义路由。

web.php

Route::get('/details', 'StudentController@display');

输出量

Laravel将数据传递到视图

with()函数

我们还可以使用with()函数将数据传递给视图。

  • 首先, 我们创建了student.blade.php文件, 其中包含页面视图。
<html>
 <body>
 <h1>Student id is : 
 <?php 
echo $id;
?>
</body>
</html>

上面的代码显示“ id”的值。

  • 现在, 我们创建了StudentController.php文件。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StudentController extends Controller
{
  public function display($id)
  {
    return view('student')->with('id', $id);
  } 
}

在上面的代码中, 我们创建了display()函数, 该函数返回student.blade.php文件的视图, 并且我们使用with()函数传递了’id’的值。 ‘with()’函数包含两个参数, 即变量名(id)和’id’的值。

  • 现在, 我们定义路线。
Route::get('/details/{id}', 'StudentController@display');

输出量

Laravel将数据传递到视图

compact()函数

compact()函数还用于将数据传递到视图。它包含一个参数, 即变量名。

让我们通过一个例子来理解。

  • 首先, 我们创建了student.blade.php文件, 其中包含页面视图。
<html>
 <body>
 <h1>Name is : 
 <?php 
echo $name;?>
</body>
</html>
  • 现在, 我们创建了StudentController.php文件。
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StudentController extends Controller
{
    public function display($name)
  {
    return view('student?, compact('name'));
  } }
  • 现在, 我们在web.php文件中定义路由。
Route::get('/details/{name}', 'StudentController@display');

输出量

Laravel将数据传递到视图

我们可以将多个参数传递给compact()函数。

让我们通过一个例子来理解。

Student.blade.php

<html>
 <body>
<h1>Students Details : <br>
<font size='5' face='Arial'>
<?php 
echo "student id is :" .$id;
echo "<br>";
echo "Student name is :" .$name;
echo "<br>";
echo "Student password is :" .$password; ?></h1>
</font>
</body></html>

StudentController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class StudentController extends Controller
{
   public function display($id, $name, $password)
  {
     return view('student', compact('id', 'name', 'password'));
  } 
}

web.php

Route::get('/details/{id}/{name}/{password}', 'StudentController@display');

输出量

Laravel将数据传递到视图

赞(0)
未经允许不得转载:srcmini » Laravel将数据传递到视图

评论 抢沙发

评论前必须登录!