{{toc}}php
server { listen 80; server_name local.laravel.com; set $root_path '/www/laravel/public/'; root $root_path; index index.php index.html index.htm; try_files $uri $uri/ @rewrite; location @rewrite { rewrite ^/(.*)$ /index.php?_url=/$1; } location ~ \.php { fastcgi_pass 127.0.0.1:9000; fastcgi_index /index.php; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~* ^/(css|img|js|flv|swf|download)/(.+)$ { root $root_path; } location ~ /\.ht { deny all; } }
數據庫配置文件在.env中,經過config/database.php來調用,以下,經過env方法來獲取變量名,若是變量沒有值則賦值 localhost之類,.env文件能夠不放在版本控制中css
'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ],
數據庫 表、字段各類操做都可在控制器中執行,見 http://laravelacademy.org/post/130.html
只要訪問該方法,則會直接影響數據庫結構html
$ php artisan migrate
$ php artisan migrate:rollback 這個命令 和 refresh命令會清掉全部的數據
$ php artisan make:migration create_articles_table --create=articals
$ php artisan make:migration add_intro_column_to_articles --table=articals
php artisan make:model Artical
laravel修改字段可經過控制器來執行, 用的是Schema門面mysql
Schema::table('users', function ($table) { $table->string('name'); });
經過命令行CURDnginx
php artisan tinker >>> $artical = new App\Artical; => App\Artical {#674} >>> $article->title='my first title'; => "my first title" >>> $article->content='content'; => "content" >>> $article->published_at=Carbon\Carbon::now(); => Carbon\Carbon {#679 +"date": "2016-10-11 11:37:54.000000", +"timezone_type": 3, +"timezone": "UTC", } >>> $artical; => App\Artical {#674} >>> $article; => {#677 +"title": "my first title", +"content": "content", +"published_at": Carbon\Carbon {#679 +"date": "2016-10-11 11:37:54.000000", +"timezone_type": 3, +"timezone": "UTC", }, } >>> $a->save(); => true >>> $a->toArray(); => [ "title" => "my first title", "content" => "content", "published_at" => Carbon\Carbon {#671 +"date": "2016-10-11 12:01:35.000000", +"timezone_type": 3, +"timezone": "UTC", }, "updated_at" => "2016-10-11 12:01:46", "created_at" => "2016-10-11 12:01:46", "id" => 1, ] 查找 >>> $first=App\Article::find(1); => App\Article {#685 id: 1, title: "my first title", content: "content", published_at: "2016-10-11 12:01:35", created_at: "2016-10-11 12:01:46", updated_at: "2016-10-11 12:01:46", } 更新 >>> $first->title='update'; => "update" >>> $first->save(); => true 條件查找 得到數據集 >>> $second=App\Article::where('content','=','content')->get(); 或者 >>> $second=App\Article::where('content','=','content')->first(); => Illuminate\Database\Eloquent\Collection {#692 all: [ App\Article {#693 id: 1, title: "update", content: "content", published_at: "2016-10-11 20:07:12", created_at: "2016-10-11 12:01:46", updated_at: "2016-10-11 12:07:12", }, ], }
總結建立表的過程:laravel
Route::get('/', function () { return view('welcome'); }); // 基礎路由 Route::get('basic1', function () { return 'hello world basic1'; }); // 基礎路由 Route::post('basic2', function () { return 'hello world basic2'; }); // 多請求路由 響應指定請求類型 Route::match(['get','post' ], 'multy1', function () { return 'multy1'; }); //多請求路由 響應全部的請求類型 Route::any('multy1', function () { return 'multy2'; }); //路由參數 Route::get('user/{id}', function ($id) { return 'userid-'.$id; }); //路由參數 非必須 Route::get('user/{name?}', function ($name=null) { return 'username-'.$name; }); //參數 正則 Route::get( 'user1/{name?}', function ($name=null) { return 'username-'.$name; })->where('name','[A-Za-z]+'); //多參數 正則 Route::get( 'user2/{id}/{name?}', function ( $id, $name=null) { return 'userid-'.$id . 'username-'.$name; })->where( [ 'id'=> '[0-9]+' , 'name'=>'[A-Za-z]+'] ); //路由別名 別名的做用並不是是經過center就能夠直接訪問,而是利用控制器或view根據別名生成url Route::get('user3',['as'=>'center',function () { return route('center'); }]); //羣組路由 前綴 Route::group( ['prefix'=>'member'],function(){ Route::get('basic1', function () { return 'hello world basic1'; }); Route::post('basic2', function () { return 'hello world basic2'; }); } );
使用artisan建立控制器
php artisan make:controller TestControllerweb
控制器目錄:app/Http/Controllers
控制器命名規則:MemberControllerajax
//路由關聯控制器 方法一: MemberController控制器的info方法 Route::get('member/info','MemberController@info'); //路由關聯控制器 方法二: 以數組的形式指定控制器和別名 Route::get('member/info1', [ 'uses' =>'MemberController@info' , 'as' => 'memberinfo1' ]); //路由關聯控制器 參數綁定 在控制器中傳入id 便可 Route::get('member/info3/{id}','MemberController@info')->where('id', '[0-9]+');
參考:http://www.ynpxrz.com/n802045c2025.aspxsql
默認使用symfony的http請求方法數據庫
public function request1(Request $request){ //1.取值 若是沒有能夠加一個默認值 '未知' $request->input('name','未知'); if( $request->has('name') ){ echo $request->input('name'); }else{ echo '無該參數'; } //2.取全部的參數 $res = $request->all(); //dd($res); //3.判斷請求類型 echo $request->method(); if( $request->isMethod('GET') ){ echo 'is get'; }else{ echo 'is not get'; } // 4.判斷 ajax請求 $request->ajax(); //5.判斷路由符合特定規則 $res = $request->is('student/*'); echo $res; //6.獲取當前url echo $request->url(); }
$arr = [ 'name' => 'alice', 'age' => '12' ]; //return response()->json($arr); // 重定向 並帶session flash,還能夠帶別的 cookie input等 return redirect('student/session2')->->with('message1', '我是快閃數據'); //重定向2 return redirect()->action('StudentController@session2')->with('message1', '我是快閃數據'); //重定向3 route 別名 return redirect()->route('student-url'); //回退 return redirect()->back();
// 1. http request session() $request->session()->put('k1','v1'); echo $request->session()->get('k1'); //2.session() session()->put('k2','v2'); echo session()->get('k2'); //3.Session類 Session::put('k3','v3'); echo Session::get('k3','default');//若是k3不存在就default //4.以數組形式存儲 Session::put(['k4'=>'v4']); echo Session::get('k4'); //5.把數據放數組中 Session::push('student','alice'); Session::push('student','alice1'); //dd( Session::get('student') );//arr //6.ds sxb 刪除session $res = Session::pull('student'); $res = Session::get('student'); dd( $res );//null //7.取出全部的值 $res = Session::all(); //8.判斷 session是某個key否存在 Session::has('k1'); //9.刪除某個key的值 Session::forget('k1'); //10. 刪除全部 Session::flush(); //11.暫存 Session::flash('flash-k1','flash-v1'); echo Session::get('flash-k1');//只能第一次取的時候有
//宣傳頁 Route::get('student/activity0','StudentController@activity0'); //活動頁 Route::group(['middleware'=>['activity'] ],function(){ Route::get('student/activity1','StudentController@activity1'); Route::get('student/activity2','StudentController@activity2'); });
public function activity0(){ return '活動即將開始,敬請期待'; } public function activity1(){ return '活動1進行中,謝謝您的參與'; } public function activity2(){ return '活動2進行中,謝謝您的參與'; }
app/Http/Middleware/Activity.php
namespace App\Http\Middleware; use Closure; //use Illuminate\Support\Facades\Auth; class Activity { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { echo '我是前置'; if( time() < strtotime('2016-10-06') ){ return redirect( 'student/activity0' ); } //正常執行 把請求扔給$next return $next($request); echo '我是後置'; } }
app/Http/Kernel.php
protected $routeMiddleware = [ 'activity' => \App\Http\Middleware\Activity::class, ];
//對應view目錄 resources/view/member/info.blade.php return view('member/info',[ 'name'=>'alice', 'age' => 18 ]); 在info.blade.php中 經過 {{ $name }} {{ $age }} 來獲取參數
在app下新建一個Member.php 模型
namespace App; use Illuminate\Database\Eloquent\Model; class Member extends Model { public static function getMember(){ return 'member name is alice'; } }
在控制器中調用Member模型:
return Member::getMember();
使用原生的sql語句操做數據庫
//數據庫 插入 retun bool $bool = DB::insert('insert into student(name,age) VALUES (?,?)',['alice',18]); var_dump($bool); //數據庫 更新 retun num 行數 $num = DB::update('update student set age = ? where name = ?',[20,'alice']); var_dump($num); //數據庫 查詢 return arr $students = DB::select( 'select * from student where id > ?', [1] ); var_dump($students); //數據庫 刪除 return num 行數 $numDelete = DB::delete('delete from student where id>?',[1]); var_dump($numDelete);
使用查詢構造器操做數據庫
//新增 return bool $bool = DB::table('student')->insert( ['name'=>'imooc','age'=>18] ); var_dump($bool); //新增 一條數據 並獲得它的自增id return id $id = DB::table('student')->insertGetId( ['name'=>'imooc1','age'=>18] ); var_dump($bool); //新增多條數據 return bool $bool = DB::table('student')->insert([ ['name'=>'imooc2','age'=>18], ['name'=>'imooc3','age'=>18], ['name'=>'imooc4','age'=>18], ['name'=>'imooc5','age'=>18], ['name'=>'imooc6','age'=>18], ]); var_dump($bool);
//更新指定內容 $num = DB::table('student')->where('id',8)->update(['age'=>30]); //指定字段自增 屬於批量操做 自減 同理 decrement $num = DB::table('student')->increment('age'); $num = DB::table('student')->where('id',8)->increment('age',3); //自增的時候修改其餘字段 $num = DB::table('student')->where('id',8)->increment('age',3,['name'=>'joe']);
$num = DB::table('student')->where('id',13)->delete(); //能夠用表達式 where('id', '>=' , 13) //清空表 不返回任何東西 DB::table('student')->truncate();
//get() 獲取表的全部數據 $students = DB::table('student')->get();
$students = DB::table('student')->orderBy('id','asc')->first();
$students = DB::table('student')->where('id','>=',2)->get(); //where()多個條件 $students = DB::table('student')->whereRaw('id>=? and age>?',[1,24])->get();
//pluck()返回結果集中指定的字段 $names = DB::table('student')->pluck('name');
//lists() 也能夠實現pluck的效果,同時 lists能夠指定某個字段爲key $names = DB::table('student')->lists('name','id');
//select 指定字段查詢 $names = DB::table('student')->select('id', 'name','age')->get();
//chunk 分段獲取數據 每次查2條 echo '<pre>'; DB::table('student')->chunk(2,function($students){ var_dump($students); return false;//指定條件下 中止查詢 }); echo '</pre>'; dd($names);
$num = DB::table('student')->count(); $v = DB::table('student')->max('age'); $v1 = DB::table('student')->min('age'); $avg = DB::table('student')->avg('age'); //平均數 $sumage = DB::table('student')->sum('age');
app/Student.php
use Illuminate\Database\Eloquent\Model; class Student extends Model { //指定表名 protected $table = 'student'; //指定id protected $primaryKey = 'id'; //指定容許批量賦值的字段 多個字段賦值 protected $fillable = ['name','age']; //指定不容許批量賦值的字段 //protected $gaurded = []; //自動維護時間戳 public $timestamps = true; //設置時間戳爲nginx時間 protected function getDateFormat(){ return time(); } //控制器裏的 $student = Student::find(15);echo $student->created_at;返回時間戳 而不是格式化後的時間 protected function asDateTime($val){ return $val; } }
//all $students = Student::all(); //find $student = Student::find(8); //atrributes裏查看 //findOrFail $student = Student::findOrFail(18);//沒找到就報錯 //使用查詢構造器 查詢 //get $students = Student::get(); //first $students = Student::where('id','>=', 8)->orderBy('age','asc')->first(); //查詢數據庫判斷結果是否爲空 $users = DB::table('users')->where('id',$id)->get(); Eloquent已經給咱們封裝幾個判斷方法以下 if ($users->first()) { // } if (!$users->isEmpty()) { // } if ($users->count()) { // } //chunk 分批 Student::chunk(2,function($students){ var_dump($students); }); // 查詢構造器的聚合函數 $num = Student::count(); $max = Student::where('id','>=', 8)->max('age');
建立數據有幾個方法:
//實例化 $student = new Student(); $student->name = 'melody1'; $student->age = 23; //保存數據到數據庫 並自動維護 created_at 和 updated_at字段 ,若是不想維護 須要在 模型中 關閉 $timestamps = false $student->save(); $student = Student::find(15); echo $student->created_at;//格式化 後的時間 2016-09-09 17:23:14 //若是不想格式化 須要在模型中 寫個函數 asDateTime
//使用create方法新增數據 批量 多個字段 $student = Student::create(['name'=> 'frank','age'=>32 ]);
//firstOrCreate() 以屬性查找,若是沒有則新增 $student = Student::firstOrCreate(['name'=> 'frank']);
//firstOrNew 以屬性查找,若是沒有則實例化一個 能夠經過 save保存到數據庫 $student = Student::firstOrNew( ['name'=> 'frank1'] ); $student->save();
$student = Student::find('27'); $student->name = 'kitty'; $bool = $student->save();
$num = Student::where('id','>=',9)->update(['age'=>36]);
Student::find('27')->delete();
Student::destroy('23','28');//批量刪除也能夠用數組 [1,2,3]
Student::where('id','>=',10)->delete();
view/layout.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel-@yield('title')</title> <style> </style> </head> <body> <div class="container"> <div class="header"> @section('header') 頭部 @show </div> <div class="main"> <div class="sidebar"> @section('sidebar') 側邊欄 @show </div> <div class="content"> @yield('content','內容區') </div> </div> <div class="footer"> @section('footer') 底部 @show </div> </div> </body> </html>
@extends('layout'); @section('title') @parent 模板 @stop @section('header') @parent header @stop @section('content') @parent content @stop
$students = Student::get(); return view('student.section1',[ 'name'=>'alice', 'students'=>$students ]);
{{--模板中輸出變量--}} {{$name}} {{-- 模板中使用php源碼 --}} <p>{{ time() }}</p> <p>{{ date('Y-m-d H:i:s',time()) }}</p> <p>{{ isset( $age ) ? $age : 'default age 30' }}</p> <p>{{ $name1 or 'default name1' }}</p> {{--原樣輸出--}} <p>{{ @name }}</p> {{--引入子勢圖--}} @include('student.comment',['message'=>'錯誤信息'])
if unless for foreach forelse
{{--流程控制--}} @if( $name == 'alice1' ) I'm alice1 @elseif( $name== 'alice' ) I'm alice @else who am I? @endif {{-- unless 是 if的取反 --}} @unless( $name=='alice1' ) <p>this is alice</p> @endunless {{--for--}} @for( $i= 0; $i<10;$i++ ) {{$i}} , @endfor {{--foreach--}} @foreach( $students as $student ) {{ $student->name }} @endforeach {{--forelse 若是有數組則輸出 若是沒有則提示我是空--}} @forelse( $students as $student) {{ $student->name }} @empty 我是空數組 @endforelse
{{--url('路由的名稱')--}} <a href="{{ url('url') }}"> url() </a>
{{--action(控制器名@方法名)--}} <a href="{{action('StudentController@url')}}">action()</a>
{{--router('別名')--}} <a href="{{route('student-url')}}">route()</a>
$students = Student::paginate(5);
{{ $students->render() }}
php artisan make:seeder AdminsTableSeeder
執行完命令後將會在 database/seeds 目錄下生成 AdminsTableSeeder.php 文件。接下來咱們定義一個數據模型工廠,在 database/factories/ModelFactory.php 中添加以下代碼:
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); $factory->define(App\Models\Admin::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; });
模型工廠定義完成後,在 AdminsTableSeeder.php 中填充數據:
<?php use Illuminate\Database\Seeder; class AdminsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { factory('App\Models\Admin',3)->create([ 'password' => bcrypt('123456') ]); } }
填充數據弄好後,在 DatabaseSeeder.php 中加入 AdminsTableSeeder 類
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $this->call(UsersTableSeeder::class); $this->call(AdminsTableSeeder::class); } }
最後執行遷移命令:
php artisan migrate --seed