laravel(四)

laravel(四)

視圖(頁(yè)面布局)

頁(yè)面布局: 指提取網(wǎng)站視圖公共部分,其他視圖文件繼承或引入

好處: 減少冗余

common.png

語(yǔ)法:

@yield('標(biāo)識(shí)')                父(公共區(qū)域)定義內(nèi)容片段,子填充
@extends('標(biāo)識(shí)')          子繼承父(公共區(qū)域)
@section('標(biāo)識(shí)', '默認(rèn)值')   子填充父(公共區(qū)域)文字
@section('標(biāo)識(shí)')              子填充父(公共區(qū)域)HTML代碼
存放子頁(yè)面內(nèi)容
@endsection
@include('視圖標(biāo)識(shí)', ['key' => 'value變量值']) 調(diào)取公共頁(yè)面(一般多個(gè)子頁(yè)面提?。?

創(chuàng)建common頁(yè)面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>laravel</title>
    <!-- Bootstrap CSS 文件 -->
    <link rel="stylesheet" href="{{ asset('admin/static') }}/bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="{{ asset('admin/static') }}/bootstrap/css/form.css">
</head>
<body>

<div class="navbar navbar-default">
    <div class="container">
        <div class="navbar-header">
            <a href="/" class="navbar-brand">首頁(yè)</a>
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#menu" aria-expanded="false">
                <span class="sr-only">菜單折疊</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>

        </div>
        <div class="collapse navbar-collapse" id="menu">
            <ul class="nav navbar-nav">
                <li class="active"><a href="/">開(kāi)發(fā)</a></li>
                <li><a href="#">列表</a></li>
                <li><a href="#">頭條</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">資訊 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">學(xué)習(xí)一</a></li>
                        <li><a href="#">學(xué)習(xí)二</a></li>
                        <li class="divider"></li>
                        <li><a href="#">技術(shù)學(xué)習(xí)</a></li>
                        <li class="divider"></li>
                        <li><a href="#">jq學(xué)習(xí)</a></li>
                    </ul>
                </li>
            </ul>
            <form class="navbar-form navbar-left">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="Search...">
                </div>
                <button type="submit" class="btn btn-default">搜索</button>
            </form>
            <ul class="nav navbar-nav navbar-right">
                @if(!session('userinfo'))
                <li><a href="{{ url('student/login')  }}">登錄</a></li>
                <li><a href="javascript:void();">注冊(cè)</a></li>
                @else
                    <li><a href="javascript:void();">歡迎 {{ Session::get('userinfo','管理員')  }}</a></li>
                    <li><a href="{{ url('student/logout')  }}">退出</a></li>
                @endif
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">相關(guān)<span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#">系列一</a></li>
                        <li class="divider"></li>
                        <li><a href="#">系列二</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</div>

@yield('body')

<!-- 尾部 -->
<div class="jumbotron" style="margin:0;">
    <div class="container">
        <span>  @2017 laravel</span>
    </div>
</div>

<!-- jQuery 文件 -->
<script src="{{ asset('admin/static') }}/jquery/jquery.min.js"></script>
<!-- Bootstrap JavaScript 文件 -->
<script src="{{ asset('admin/static') }}/bootstrap/js/bootstrap.min.js"></script>

</body>
<link rel="stylesheet" type="text/css" href="{{ asset('css') }}/sweetalert.min.css">
<script type="text/javascript" src="{{ asset('js') }}/sweetalert.min.js"></script>
<script type="text/javascript">
    @if (Session::has('tips'))
    swal("{{Session::get('tips')}}", "系統(tǒng)提示","{{Session::get('state')}}")
    @endif
</script>
</html>



add頁(yè)面

@extends('admin.student.common')

@section('body')
    <!-- 頭部 -->
    <div class="jumbotron jump">
        <div class="container">
            <h2>玩轉(zhuǎn)laravel</h2>

            <p> 玩轉(zhuǎn)- laravel</p>
        </div>
    </div>

    <!-- 中間內(nèi)容區(qū)局 -->
    <div class="container">
        <div class="row">

            <!-- 左側(cè)菜單區(qū)域   -->
            <div class="col-md-3">
                <div class="list-group">
                    <a href="{{ url('student/index')  }}" class="list-group-item ">學(xué)生列表</a>
                    <a href="javascript:void(0);" class="list-group-item active">新增學(xué)生</a>
                </div>
            </div>

            <!-- 右側(cè)內(nèi)容區(qū)域 -->
            <div class="col-md-9">

                <!-- 所有的錯(cuò)誤提示 -->
                <div class="alert alert-danger">
                    @if (count($errors) > 0)
                        <div class="alert alert-danger">
                            <ul>
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                </div>

                <!-- 自定義內(nèi)容區(qū)域 -->
                <div class="panel panel-default">
                    <div class="panel-heading">新增學(xué)生</div>
                    <div class="panel-body">
                        <form class="form-horizontal" action="{{ url('student/add')  }}" method="post">
                            <div class="form-group">
                                <label for="name" class="col-sm-2 control-label">姓名</label>

                                <div class="col-sm-5">
                                    <input type="text" class="form-control" name="uname" id="name" placeholder="請(qǐng)輸入學(xué)生姓名">
                                </div>
                                <div class="col-sm-5">
                                    <p class="form-control-static text-danger">{{ $errors->first('uname') }}</p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="age" class="col-sm-2 control-label">密碼</label>

                                <div class="col-sm-5">
                                    <input type="text" class="form-control" name="pwd" id="age" placeholder="請(qǐng)輸入密碼">
                                </div>
                                <div class="col-sm-5">
                                    <p class="form-control-static text-danger">{{ $errors->first('pwd') }}</p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="age" class="col-sm-2 control-label">年齡</label>

                                <div class="col-sm-5">
                                    <input type="text" class="form-control" id="age" name="age" placeholder="請(qǐng)輸入學(xué)生年齡">
                                </div>
                                <div class="col-sm-5">
                                    <p class="form-control-static text-danger">{{ $errors->first('age') }}</p>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label">性別</label>

                                <div class="col-sm-5">
                                    <label class="radio-inline">
                                        <input type="radio" name="sex" value="1"  > 男
                                    </label>
                                    <label class="radio-inline">
                                        <input type="radio" name="sex" value="2" checked="checked"> 女
                                    </label>
                                </div>
                                <div class="col-sm-5">
                                    <p class="form-control-static text-danger"></p>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-primary">提交</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

            </div>
        </div>
    </div>

@endsection

index 頁(yè)面..等.

@extends('admin.student.common')

@section('body')

<div class="jumbotron jump">
    <div class="container">
        <h2>玩轉(zhuǎn)laravel-之首頁(yè)</h2>

        <p> 玩轉(zhuǎn)- laravel</p>
    </div>
</div>

<!-- 中間內(nèi)容區(qū)局 -->
<div class="container">
    <div class="row">

        <!-- 左側(cè)菜單區(qū)域   -->
        <div class="col-md-3">
            <div class="list-group">
                <a href="{{ url('student/index')  }}" class="list-group-item active">學(xué)生列表</a>
                <a href="{{ url('student/add')  }}" class="list-group-item">新增學(xué)生</a>
            </div>
        </div>

        <!-- 右側(cè)內(nèi)容區(qū)域 -->
        <div class="col-md-9">

            <!-- 成功提示框 -->
            <div class="alert alert-success alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <strong>成功!</strong> 操作成功提示!
            </div>

            <!-- 失敗提示框 -->
            <div class="alert alert-danger alert-dismissible" role="alert">
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <strong>失敗!</strong> 操作失敗提示!
            </div>

            <!-- 自定義內(nèi)容區(qū)域 -->
            <div class="panel panel-default">
                <div class="panel-heading">學(xué)生列表</div>
                <table class="table table-striped table-hover table-responsive">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>年齡</th>
                        <th>性別</th>
                        <th>添加時(shí)間</th>
                        <th width="120">操作</th>
                    </tr>
                    </thead>
                    <tbody>

                    @foreach($students as $student)
                        <tr>
                            <th scope="row">{{ $student->id }}</th>
                            <td>{{ $student->uname }}</td>
                            <td>{{ $student->age }}</td>
                            <td>
                                @if($student->sex  == 1)
                                    男
                                @else
                                    女
                                @endif
                            </td>
                            <td>{{ $student->created_at }}</td>
                            <td>
                                <a href="">詳情</a>
                                <a href="{{  url("student/upd?id=$student->id ") }}">修改</a>
                                <a href="{{  url("student/del?id=$student->id ") }}" onclick="return confirm('確定要?jiǎng)h除嗎?')">刪除</a>
                            </td>
                        </tr>
                    @endforeach

                    </tbody>
                </table>
            </div>

            <!-- 分頁(yè)  -->
            <div>
                {{ $students->links() }}
            </div>

        </div>
    </div>
</div>

@endsection

會(huì)話技術(shù)

session會(huì)話

定義路由

Route::get('/day4/t1', 'Admin\Day4Controller@t1');
Route::get('/day4/t2', 'Admin\Day4Controller@t2');

創(chuàng)建控制器方法

語(yǔ)法:

位置:app\config\session.php文件

腳下留心:Laravel重寫(xiě)了session機(jī)制

在config\session.php 中 將expire)on_close改為true // 瀏覽器關(guān)閉清空session

HTTP Request 的session方法

設(shè)置:            Session::put(鍵,值);
獲取指定:          Session::get(鍵 [,默認(rèn)值])
獲取所有:          Session::all()
判斷:            Session::has(key)

刪除指定:          Session::forget(key) 
刪除所有:      Session::flush() 
壓入session數(shù)組:Session::push(key, value)
獲取后刪除:     Session::pull(key) 
閃存:            Session::flash(key, value)  
輔助函數(shù)
設(shè)置:session([鍵1=>值1,...,鍵n=>值n])
獲?。簊ession(鍵)

練習(xí)

#設(shè)置session(需求:uname=itcast,age=18,stu=[uname=xiaoze,age=18])
#獲取指定uname和age
#刪除age指定
#獲取全部
public function t1()
{
    #設(shè)置session(需求:uname=itcast,age=18,stu=[uname=xiaoze,age=18])
    Session::put('uname', 'itcast');
    Session::put('age', '18');
    Session::put('stu', ['uname'=>'xiaoze', 'age'=>18]);
     #獲取指定uname和age
    echo Session::get('uname');
    echo Session::get('age');
    #刪除age指定
    Session::forget('age');
    #獲取全部
    dd(Session::all());
}

Cookie會(huì)話

設(shè)置:Cookie::make(鍵,值)

獲?。篊ookie::get(鍵)

$data = Cookie::make('username','itcast')
return redirect(url('/day4/t2))->withCookie($data);
echo Cookoe::get('username')

中間件

中間件:就是HTTP請(qǐng)求交給控制器方法前的過(guò)濾層

將HTTP請(qǐng)求交給控制器方法前先交給另一個(gè)方法處理

語(yǔ)法:

語(yǔ)法:php artisan make:middleware 中間件名稱(chēng)

位置:app\Http\Middleware

步驟1:創(chuàng)建中間件

步驟2:激活中間件(app\Http\Kernel.php)

步驟3:使用修改路由聲明哪些路由需要通過(guò)中間件過(guò)濾

創(chuàng)建中間件

php artisan make:middleware CheckTest

激活中間件 http\kemel.php中

protected $routeMiddleware = [

    //新增

    'CheckTest' => \app\http\middleware\CheckTest::class 

];


laravel控制器數(shù)據(jù)驗(yàn)證

JS驗(yàn)證表單數(shù)據(jù):1-提高用戶(hù)體驗(yàn)度,2-減少不必要的http請(qǐng)求

PHP數(shù)據(jù)驗(yàn)證:增強(qiáng)安全性

控制器直接使用validate方法

$this->validate($request,驗(yàn)證規(guī)則 [,自定義提示信息])

單獨(dú)創(chuàng)建驗(yàn)證類(lèi)

語(yǔ)法:php artisan make:request 驗(yàn)證類(lèi)名稱(chēng)   (注:Check模型名  大駝峰)
位置:app\Http\Requests目錄

視同validator門(mén)面驗(yàn)證

$validator = Validator::make(數(shù)組,驗(yàn)證規(guī)則 [,自定義提示信息])
$validator->passes()            判斷是否成功:true-成功沒(méi)有問(wèn)題,false-失敗有問(wèn)題
$validator->fails()             判斷是否失?。簍rue-失敗有問(wèn)題,false-成功沒(méi)問(wèn)題
$validator->messages()           獲取錯(cuò)誤信息

驗(yàn)證規(guī)則

required: 不能為空
max:255最長(zhǎng)255個(gè)字符,
min:1最少1個(gè)字符
email:驗(yàn)證郵箱是否合法
confirmed:驗(yàn)證兩個(gè)字段是否相同,如果驗(yàn)證的字段是password,則必須輸入一個(gè)與之匹配的password_confirmation字段
integer:驗(yàn)證字段必須是整型
ip:驗(yàn)證字段必須是IP地址
numeric 驗(yàn)證字段必須是數(shù)值
max:value 驗(yàn)證字段必須小于等于最大值,和字符串,數(shù)值,文件字段的size規(guī)則一起使用。
min:value 驗(yàn)證字段的最小值,對(duì)字符串、數(shù)值、文件字段而言,和size規(guī)則使用方式一致。
size:value 驗(yàn)證字段必須有和給定值value想匹配的尺寸,對(duì)字符串而言,value是相應(yīng)的字符數(shù)目,對(duì)數(shù)值而言,value是給定整型值;對(duì)文件而言,value是相應(yīng)的文件字節(jié)數(shù)。
string 驗(yàn)證字段必須是字符串
unique:表名,字段,需要排除的ID

規(guī)則手冊(cè):http://laravelacademy.org/post/6768.html#toc_17 
&多學(xué)一招:多個(gè)驗(yàn)證規(guī)則可以通過(guò) "|" 字符進(jìn)行隔開(kāi)
直接使用validate方法
#數(shù)據(jù)過(guò)濾
#語(yǔ)法:$this->validate($request,驗(yàn)證規(guī)則 [,提示信息])
$this->validate($request, [
    'uname' => 'required|min:3|max:8',
    'pwd' =>  'required|min:6|max:30',
    'age' => 'required|integer|between:1,100',
    'sex' => 'required|integer|between:1,2',
], [
    'uname.required' => '用戶(hù)名必須',
    'uname.min' => '用戶(hù)名至少3個(gè)字符',
]);

輸出視圖

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

漢化提示信息

&漢化提示信息
1)下載:https://github.com/caouecs/Laravel-lang 
2)將src\zh-CN移動(dòng)到resources\lang\中并更名為zh_CN
修改config\app.php文件

將改成'locale' => 'zh_CN',
刪除自定義提示查看效果
單獨(dú)創(chuàng)建驗(yàn)證類(lèi)
創(chuàng)建驗(yàn)證類(lèi): php artisan make:request CheckStudent
#輸入內(nèi)容:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CheckStudent extends FormRequest
{
    public function authorize()
    {
        //是否開(kāi)啟驗(yàn)證:true-是,false-頭
        return true;
    }
    
    public function rules()
    {
        if ($this->isMethod('get')) return [];
        return [
            'uname' => 'required|min:3|max:8',
            'pwd' =>  'required|min:6|max:30',
            'age' => 'required|integer|between:1,100',
            'sex' => 'required|integer|between:1,2',
        ];
    }
    
    public function messages()
    {
        return [
            'uname.required' => '用戶(hù)名必須',
            'uname.min' => '用戶(hù)名至少3個(gè)字符',
        ];
    }
}

控制器調(diào)用

public function add(\App\Http\Requests\CheckStudent $request){
    xxx
}
使用validator門(mén)面控制器
直接在控制器里進(jìn)行驗(yàn)證
#數(shù)據(jù)過(guò)濾
$validator = Validator::make($postData, [
    'uname' => 'required|min:3|max:8',
    'pwd' =>  'required|min:6|max:30',
    'age' => 'required|integer|between:1,100',
    'sex' => 'required|integer|between:1,2',
]);
//會(huì)否驗(yàn)證失?。簍rue-驗(yàn)證失敗,false-驗(yàn)證成功
if ($validator->fails()) {
    //獲取錯(cuò)誤信息
    //dd($validator->messages());
    return redirect(url('/student/add'))->withErrors($validator);
}

顯示單個(gè)錯(cuò)誤

語(yǔ)法:{{ $errors->first(name屬性值) }}

多表查詢(xún)

安裝Laravel開(kāi)發(fā)調(diào)試工具(注:同TP默認(rèn)的Trace調(diào)試工具)

文檔:http://laravelacademy.org/post/2774.html

composer require barryvdh/laravel-debugbar

在config\app.php 注冊(cè)激活

'providers' => [
    Barryvdh\Debugbar\ServiceProvider::class,
]

連表查詢(xún)語(yǔ)法:

DB::table(表1)/ 模型名
leftJoin(表2,‘表1.公共字段’,‘=’,‘表2.公共字段’)
->get();
查詢(xún)構(gòu)建器

定義路由..

創(chuàng)建控制器方法

#練習(xí)(一對(duì)一關(guān)系:一篇文章屬于一個(gè)用戶(hù))
$articles = DB::table('article')->leftJoin('stu', 'article.uid', '=', 'stu.id')->get();
foreach ($articles as $article)
{
    echo '文章ID:'.$article->aid.',文章標(biāo)題:'.$article->title.'<br />';
    echo '用戶(hù)ID:'.$article->id.',用戶(hù)昵稱(chēng):'.$article->uname.'<hr />';
}
#練習(xí)(一對(duì)多關(guān)系:一個(gè)用戶(hù)擁有多篇文章)
$stus = DB::table('stu')->leftJoin('article', 'stu.id', '=', 'article.uid')->get();
foreach ($stus as $stu)
{
    echo '用戶(hù)ID:'.$stu->id.',用戶(hù)昵稱(chēng):'.$stu->uname.'<br />';
    echo '文章ID:'.$stu->aid.',文章標(biāo)題:'.$stu->title.'<hr />';
}
模型

創(chuàng)建模型

php artisan make:model Http\Models\Article
php artisan make:model Http\Models\Stu

模型對(duì)應(yīng)表

<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Stu extends Model
{
    /**
     * 聲明表名
     *
     * @var        string
     */
    protected $table = 'stu';
}

<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    /**
     * 聲明表名
     *
     * @var        string
     */
    protected $table = 'article';
}

練習(xí)

#練習(xí)(一對(duì)一關(guān)系:一篇文章屬于一個(gè)用戶(hù))
$articles = Article::leftJoin('stu', 'article.uid', '=', 'stu.id')->get();
foreach ($articles as $article)
{
    echo '文章ID:'.$article->aid.',文章標(biāo)題:'.$article->title.'<br />';
    echo '用戶(hù)ID:'.$article->id.',用戶(hù)昵稱(chēng):'.$article->uname.'<hr />';
}
#練習(xí)(一對(duì)多關(guān)系:一個(gè)用戶(hù)擁有多篇文章)
$stus = Stu::leftJoin('article', 'stu.id', '=', 'article.uid')->get();
foreach ($stus as $stu)
{
    echo '用戶(hù)ID:'.$stu->id.',用戶(hù)昵稱(chēng):'.$stu->uname.'<br />';
    echo '文章ID:'.$stu->aid.',文章標(biāo)題:'.$stu->title.'<hr />';
}
關(guān)聯(lián)模型

一對(duì)一

步驟1:定義模型
public function  推薦表名 () 
{
return $this->hasOne(關(guān)聯(lián)模型命名空間,關(guān)聯(lián)模型公共字段,本模型公共字段);
}

步驟2:模型名::with(推薦表名)->get()
步驟3:
foreach($模型名s as $模型名) {
     獲取當(dāng)前模型對(duì)應(yīng)的表數(shù)據(jù) $模型名->字段名
     獲取當(dāng)前模型關(guān)聯(lián)表數(shù)據(jù)   $模型名->with處名稱(chēng)->關(guān)聯(lián)模型字段名;
}

一對(duì)多

步驟1:定義模型
public function  推薦表名s () 
{
return $this->hasMany(關(guān)聯(lián)模型命名空間,關(guān)聯(lián)模型公共字段,本模型公共字段);
}

步驟2:模型名::with(推薦表名s)->get()
步驟3:
foreach($模型名s as $模型名) {
     獲取當(dāng)前模型對(duì)應(yīng)的表數(shù)據(jù) $模型名->字段名
     獲取當(dāng)前模型關(guān)聯(lián)表數(shù)據(jù)  (腳下留心:多條數(shù)據(jù))
foreach($模型名->with處名稱(chēng) as $關(guān)聯(lián)表名) {
    $關(guān)聯(lián)表名->關(guān)聯(lián)表字段
}
}

Stu表

<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Stu extends Model
{
    protected $table = 'stu';

    public function articles()
    {
        return $this->hasMany('\App\Http\Models\Article','uid','id');
    }
}

Stundent

<?php

namespace App\Http\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    /**
     * 設(shè)置表名
     * @var string
     */
    protected $table = 'student';

    /**
     * 聲明可以批量設(shè)置的屬性
     * @var array
     */
    protected $fillable   =  ['uname', 'pwd', 'age', 'sex'];

    /**
     * Unix時(shí)間戳填充數(shù)據(jù)(注:默認(rèn)托管創(chuàng)建于更新于)
     * @var string
     */
    protected $dateFormat = 'U';
}

練習(xí)

#關(guān)聯(lián)模型語(yǔ)法,模型名::with(推薦表名) ->get() 

#練習(xí)(一對(duì)一關(guān)系:一篇文章屬于一個(gè)用戶(hù))
$articles = Article::with('stu')->get();
foreach($articles as $article) {
    echo '文章ID:'.$article->aid.',文章標(biāo)題:'.$article->title.'<br />';
    #說(shuō)明:with語(yǔ)法獲取關(guān)聯(lián)數(shù)據(jù)
    #語(yǔ)法:$小對(duì)象->with處的名->關(guān)聯(lián)模型數(shù)據(jù)庫(kù)字段名
    echo '用戶(hù)ID:'.$article->stu->id.',用戶(hù)昵稱(chēng):'.$article->stu->uname.'<hr />';
}
#練習(xí)(一對(duì)多關(guān)系:一個(gè)用戶(hù)擁有多篇文章)
$stus = Stu::with('articles')->get();
foreach($stus as $stu) {
    echo '用戶(hù)ID:'.$stu->id.',用戶(hù)昵稱(chēng):'.$stu->uname.'<br />';
    #說(shuō)明:with語(yǔ)法獲取關(guān)聯(lián)數(shù)據(jù)
    #語(yǔ)法:$小對(duì)象->with處的名稱(chēng)   是一個(gè)大對(duì)象  里面有多條數(shù)據(jù)(多個(gè)小對(duì)象)
    foreach ($stu->articles as $article) {
        echo '文章ID:'.$article->aid.',文章標(biāo)題:'.$article->title.'<br />';
    }
    echo '<hr />';
}

路由

理解RESTful

RESTful 是目前最流行的一種互聯(lián)網(wǎng)軟件架構(gòu)(思想)

RESTful表.png
tp5.png

創(chuàng)建資源控制器路由:Route::resource(URL信息,控制器);

Route::resource('/order','Admin/OrderController')

創(chuàng)建資源控制器:php artisan make:controller 平臺(tái)名\控制器名Controller --resource

php artisan make:controller Admin\OrderController --resource

緩存/配置文件/文件存儲(chǔ)-上傳

緩存

手冊(cè): http://laravelacademy.org/post/6858.html

存儲(chǔ)路徑:storage\framework\cache

設(shè)置:Cache::put(鍵,值,緩存時(shí)間/分鐘)

獲?。篊ache::get(鍵

//緩存
public function t5()
{
    #需求1:緩存用戶(hù)信息(user1),id=1,uname=itcast,age=18
    Cache::put('user1', [
        'id' => 1,
        'uname' => 'itcast',
        'age' => 18
    ], 3600);
    #需求2:獲取用戶(hù)信息(user1)
    $data = Cache::get('user1');
    print_r($data);
}

配置文件

手冊(cè): http://laravelacademy.org/post/6677.html

語(yǔ)法:config(config目錄下的配置文件名稱(chēng).鍵)

#需求1:獲取app配置文件中時(shí)區(qū)
echo config('app.timezone') . '<br />';
#需求2:獲取緩存存放目錄
echo config('cache.stores.file.path');

文件存儲(chǔ)-上傳

語(yǔ)法:

$request->hasFile(上傳框name屬性值) 
$request->file(上傳框name屬性值)->isValid()
$filename = $request->file(上傳框name屬性值)->store(子路徑,存儲(chǔ)驅(qū)動(dòng)器名稱(chēng));
----------------------------------------------
存儲(chǔ)驅(qū)動(dòng)器的名稱(chēng):對(duì)應(yīng)config/filesystems.php文件的聲明
子路徑:指會(huì)在config/filesystems.php文件聲明的上傳文件夾下再創(chuàng)建一個(gè)文件

定義any路由

創(chuàng)建控制器方法

public function t6(Request $request)
{
    #1.判斷提交方式
    if ($request->isMethod('post')) {

        #2.檢測(cè)是否上傳文件和是否成功將本地文件上傳到服務(wù)器
        if ($request->hasFile('image')  && $request->file('image')->isValid()) {
            #語(yǔ)法:相當(dāng)于move_upload_file
            #$filename = $request->file(上傳框name屬性值)->store(子路徑,存儲(chǔ)驅(qū)動(dòng)器名稱(chēng));
            
            $filename = $request->file('image')->store(date('Y-m-d', time()), 'uploads');
            echo $filename;
        } else {
            die('上傳失敗');
        }
        
    } else {
        #2.加載視圖
        return view('admin.day4.t6');
    }
}

修改config\filesystems.php

在disks數(shù)組中新增

'uploads'=>[
    'driver'=>'local', #存儲(chǔ)方式: local本地
    'root'=>public_path('uploads')  #存放位置: public/uploads
],

創(chuàng)建表單

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="{{ url('day4/t6') }}" enctype="multipart/form-data" method="post">
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
        <input type="file" name="image" /> <br> 
        <input type="submit" value="上傳" /> 
    </form> 
</body>
</html>

其他

PHP use 使用場(chǎng)景(or or and 數(shù)據(jù)操作)
or or and.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,695評(píng)論 19 139
  • Laravel 學(xué)習(xí)交流 QQ 群:375462817 本文檔前言Laravel 文檔寫(xiě)的很好,只是新手看起來(lái)會(huì)有...
    Leonzai閱讀 8,721評(píng)論 2 12
  • 一. 說(shuō)明 以下內(nèi)容大部分引用Laravel China社區(qū)的文章 - 分享下團(tuán)隊(duì)的開(kāi)發(fā)規(guī)范 ——《Laravel...
    knghlp508閱讀 8,016評(píng)論 0 28
  • 介紹 Laravel 是一款 MVC架構(gòu)、 目前最流行的 PHP框架。 Laravel的優(yōu)點(diǎn)在于: 豐富的comp...
    那就遠(yuǎn)走閱讀 8,198評(píng)論 3 18
  • Laravel框架一:原理機(jī)制篇 Laravel作為在國(guó)內(nèi)國(guó)外都頗為流行的PHP框架,風(fēng)格優(yōu)雅,其擁有自己的一些特...
    Mr_Z_Heng閱讀 3,957評(píng)論 0 13

友情鏈接更多精彩內(nèi)容