6.控制器、视图、变量
在视图中,首页模板继承了布局模板,并替换了其中的区块,形成了首页。但是当时是在模板中直接赋值,在真正的项目中是不会这么做的,一般都会通过变量来解决,这就需要和控制器联系起来了。
控制器
public function index()
{
$title = 'this is the homepage title';
$content = 'this is the homepage content';
$assign = compact('title', 'content');
return view('home.index.index', $assign);
}
视图
@extends('layout.home')
@section('title', $title)
@section('content')
{{ $content }}
@endsection
温馨提示:$assign类型必须为数组
7.数据库
虽然上面使用了变量,但是变量也是一个固定的字符串,还是不够灵活,此时我们就需要和数据库相结合。
特别说明:暂不细究是怎么来的,先学会怎么用
7.1 连接数据库
我们找到.env文件,只需要把关于DB的部分改为我们的环境参数即可。
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
7.2 如何使用
首先自然需要引入DB类
use Illuminate\Support\Facades\DB;
那么如何使用呢?首先我们需要定位到具体文件,看看里面到底包含了什么方法,我们才能根据情况使用。
我们需要的文件路径为项目目录下的vendor/laravel/framework/src/Illuminate/Database/Connection.php,我们可以看到很多方法,比如我们常用的增删改查。
温馨提示:假设数据库中有表site,并且site中有title和content字段,并且有一条记录。
public function index()
{
$siteInfo = DB::selectOne('select title,content from site');
$assign = get_object_vars($siteInfo);
return view('home.index.index', $assign);
}
需要注意的是selectOne出来的数据是对象,view需要的是数组,所以我们需要转换下。
如此一来我们就成功的从数据库调取了一条数据并且赋值给了模板使用。
完整代码如下
<?php
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class IndexController extends Controller
{
public function index()
{
$siteInfo = DB::selectOne('select title,content from site');
$assign = get_object_vars($siteInfo);
return view('home.index.index', $assign);
}
}
特别说明: 因为DB类和模型都涉及到了查询构造器,统一在模型中介绍,这里不再单独介绍。