packagelist 安装 debugbar
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
echo "In home";
});
Route::any('/all', function () {
echo "In all";
});
Route::any('/param/{id}', function ($id) {
echo "In one param $id";
});
Route::any('/param/{id?}', function ($id = 0) {
echo "In two param $id";
});
Route::any('/testparam', function () {
echo "In two param echo {$_GET['id']}";
});
Route::post('/other', function () {
echo "In other";
});
Route::match(['post', 'get'], '/test', function(){
echo "In test";
})->name('test');
// php artisan route:list //查看路由信息
// echo route('test'); 结果 http://192.168.1.91/test
// "/group/users" 匹配前面的路由 "group", 然后匹配后面的路由"users"
Route::group(["prefix" => "group"], function(){
Route::any("users", function(){
echo "In group users";
echo route('test');
});
Route::any("others", function(){
echo "In group others";
});
});
//路由调用控制器
Route::get('/goods/order',"GoodsOrderController@index");
// 在 App/Http/Controllers/Home 创建控制器 php artisan make:controller Home/testController
//调用目录下的控制器
Route::get('/home/test',"Home\TestController@index");
//接收用户参数
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class GoodsOrderController extends Controller
{
public function index(){
echo "In GoodsOrderController index method";
$request = Request();
//获取请求方法
$request->method()
//获取请求数据
$request->all(); //获取全部
$request->only(['id', 'name']); //获取指定名字的值
$temp = $request->except(['id']); //获取除了id以外的值
$temp = $request->has(['id']);
dd($temp);
}
}
在config/app.php/ aliases数组中定义类别名, use的时候可以使用别名
laraver里使用dd() == var_dump(); + die();
/App/.env 中配置数据库连接参数
/app/config/database.php 会读取 .env
dabases.php 中数据库严格模式 'strict' => false,简易改为false
数据库操作
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class GoodsOrderController extends Controller
{
public function index(){
$result = DB::table("test2")->insert(
['name' => "李二蛋啊", 'age' => 18],
["name" => "钢蛋儿啊" , 'age' => 19]
);
dd($result);
$result = DB::table("test2")->insertGetId(
['name' => "李二蛋啊啊啊啊", 'age' => 18]
);
dd($result);
$result = DB::table("test2")->where("age", "=", "18")->update(
['name' => "李金蛋"]
);
$result = DB::table("test2")->where("age", "=", 18)->increment("age", 1);
$result = DB::table("test2")->where("age", "=", 19)->get();
//不写就是andWhere, orWhere需要写orWhere
$result = DB::table("test2")->where("age", "=", 19)->where("name", "=", "李刚蛋")->get();
$result = DB::table("test2")->orWhere("age", "=", 19)->where("name", "=", "李刚蛋")->get();
$result = DB::table("test2")->whereNotIn("age", [19,20,30])->get();
$result = DB::table("test2")->select("name as other_name")->where("age", "=", 19)->get();
$result = DB::table("test2")->select("name as other_name")->where("age", "=", 19)->orderBy("age", "asc")->orderBy("name","desc")->get();
$result = DB::table("test2")->whereIn("age", [19,20,30])->offset(1)->limit(2)->get();
$result = DB::table("test2")->whereIn("age", [19,20,30])->first();
dd($result);
$result = DB::table("test2")->whereIn("id", [1])->delete();
//原生 sql 更新
$result = DB::statement("insert test2 values(default, '李二蛋', '18')");
//原生查询
$result = DB::select("select * from test2");
}
}
视图
//调用 resources\views\home\test目录下的 testview date 为传递参数
return View("home.test.testview", ["date" => date("Y-m-d H:i:s", time())]);
//视图里引用
<h1>hellow testview {{$date}}</h1>
//模版继承 -- 父类
<script src="{{asset('javascript/test.js')}}"></script>
<h1>我是头部</h1>
<!--标记将要被替换的位置-->
@yield('mainbody')
<h1>我是尾部</h1>
<!--标记将要被替换的位置-->
@yield("end");
//子类
<!--继承模版-->
@extends('home.layout.parent')
<!--指定要替换的位置为父类里的yield("mainbody")-->
@section("mainbody")
<div>正文</div>
@endsection
<!--指定要替换的位置为父类里的yield("end")-->
@section("end");
<h1>结尾</h1>
@endsection
<!-- 包含其他模版文件, 其他模版文件如果有变量, 需要在调用当前模版控制器中传入 -->
@include("home.test.testview")
//获得csrf_token
<input type="hidden" name="_token" value="{{csrf_token()}}}">
//和上面效果一样
{{csrf_field()}}
//去 app\Http\Middleware\VerifyCsrfToken.php 这个中间件修改csrf验证例外
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
"/home/test"
];
}
Active Record
php artisan make:model Home/Test2
class GoodsOrderController extends Controller
{
public function index(Request $request){
$test2 = new Test2();
$test2->name = "李刚蛋丫";
$test2->age = 20;
$result = $test2->save();
dd($result);
}
}
//request 直接填充数据
class GoodsOrderController extends Controller
{
public function index(Request $request){
$db = new Test2();
$db->fill($request->all());
$db->save();
dd($db);
}
}
//更新
class GoodsOrderController extends Controller
{
public function index(Request $request){
//$result = Test2::find(5)->toArray();
//Test2::where("id", "=", "5")->get()->toArray();
//$result = Test2::where("id", "=", "5")->update(["age" => 22]);
//$result = Test2::where("age","=", "18")->get();
// $result = $result[0]->delete();
$result = Test2::find(5);
$result->name = "李二丫";
$result = $result->save();
dd($result);
}
}
//验证数据
//控制器里
class GoodsOrderController extends Controller
{
public function index(Request $request){
if($request->method() == "GET"){
return View("home/test/child");
}else{
$result = $this->validate($request, [
"name" => "required|min:2|max:20",
"age" => "required|integer|min:1|max:200",
]);
dd($result);
}
}
}
//模型里
<!--继承模版-->
@extends('home.layout.parent')
<!--指定要替换的位置为父类里的yield("mainbody")-->
@section("mainbody")
@if ($errors->hasBag())
<?php $bags = $errors->getBags();
$errorsArray = $bags['default']->all();
?>
@foreach($errorsArray as $key => $value)
<h1><?php var_dump($value)?></h1>
@endforeach
@endif
{{--<h1><?php dd($errors); ?></h1>--}}
<div>正文</div>
<form action="/goods/order/2" method="post">
<input type="text" name="name" value=""> <br/>
<input type="text" name="age" value=""> <br/>
<input type="submit" value="提交">
</form>
@endsection
<!--指定要替换的位置为父类里的yield("end")-->
@section("end");
<h1>结尾</h1>
@endsection
<!-- 包含其他模版文件, 其他模版文件如果有变量, 需要在调用当前模版控制器中传入 -->
<input type="hidden" name="_token" value="{{csrf_token()}}}">
//和上面效果一样
{{csrf_field()}}
//搜索语言包
https://packagist.org/packages/laravel-lang/lang
//安装语言包
php -d memory_limit=-1 /usr/local/bin/composer require laravel-lang/lang:~7.0
复制语言包到 /resources/lang
修改 config/app.php 'locale' => 'zh-CN',
上传文件
//上传文件
class GoodsOrderController extends Controller
{
public function index(Request $request){
if($request->method() == "GET"){
return View("home/test/child");
}else{
if($request->hasFile("avatar") && $request->file("avatar")->isValid()){
// dd($request->file("avatar")->getSize());
// dd($request->file("avatar")->getMimeType());
$request->file("avatar")->move("./upload", time().uniqid().".".$request->file("avatar")->getClientOriginalExtension());
}
}
}
}
分页
class GoodsOrderController extends Controller
{
public function index(Request $request){
$data = Test2::where("id", ">", "1")->paginate(2);
// foreach ($data as $key => $value){
// var_dump($value->id);
// }
return View("home.test.child", ["data" => $data]);
}
}
//视图中显示分页连接
{{$data->links()}}
//验证码
1. composer 安装验证码代码
php -d memory_limit=-1 /usr/local/bin/composer require mews/captcha
2. 设置依赖注入
Find the providers key in config/app.php and register the Captcha Service Provider.
'providers' => [
// ...
Mews\Captcha\CaptchaServiceProvider::class,
]
3.别名
'aliases' => [
// ...
'Captcha' => Mews\Captcha\Facades\Captcha::class,
]
4.生成配置文件
php artisan vendor:publish
5.视图
<p>' . captcha_img() . '</p>
<p><input type="text" name="captcha"></p><br/>
//纯图片url captcha_src();
//控制器验证验证码
class GoodsOrderController extends Controller
{
public function index(Request $request)
{
if ($request->method() == "GET") {
return View("home/test/child", ["data" => []]);
} else {
$result = $this->validate($request, [
"name" => "required|min:2|max:20",
"age" => "required|integer|min:1|max:200",
"captcha" => "required|captcha",
]);
dd($result);
}
}
//配置提示信息中文
/resources/lang/zh-CN/validation.php
attributes 修改对应值
}
迁移文件
//创建迁移文件
php artisan make:migration create_goods_table
//创建的文件放在 /database/migrations
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateGoodsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('goods', function (Blueprint $table) {
$table->increments('goods_id');
$table->string("title");
$table->string("content");
$table->string("price");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('goods');
}
//数据迁移执行
// 第一次执行数据迁移, 需创建迁移操作记录表
php artisan migrate:install
//执行建表
php artisan migrate
//回滚上一次建表操作
php artisan migrate:rollback
}
//创建填充器
php artisan make:seeder GoodsTableSeeder
//创建好的文件放在 /database/seeds
//文件内容
<?php
use Illuminate\Database\Seeder;
class GoodsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$data = [
[
"title" => "啊啊啊啊",
"content" => "啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊",
"price" => 32.81,
],
[
"title" => "嘀嘀嘀嘀",
"content" => "嘀嘀嘀嘀弟弟IDID",
"price" => 3.36,
],
[
"title" => "大大大大大",
"content" => "哒哒哒嗒嗒嗒",
"price" => 5.25,
],
];
\Illuminate\Support\Facades\DB::table("goods")->insert($data);
}
}
//执行数据填充
//在控制台中执行`composer dump-autoload`,然后再执行`php artisan db:seed`.
php artisan db:seed --class=GoodsTableSeeder
//相应数据
return response()->json($result);
//重定向
return redirect("/goods/order/{Tid}");
//使用session
Session::put("user_id", 10086);
echo Session::get("user_id");
//使用cache
/config/cache.php
'default' => env('CACHE_DRIVER', 'file'),
//先找.env 的 CACHE_DRIVER, 如果没有, 使用file.
//file缓存的配置在下面指定, 也可指定database 或者 memcached
//优先使用.env里的值
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
],
]
配置 .env
CACHE_DRIVER=file //配置cache
//使用cache
Cache::add("name", "李二蛋", 1); //1分钟
sleep(3);
echo Cache::get("name");
联表查询
$request = DB::table("test2 as T2")->select("T2.id as T2_id","T2.name", "G1.title", "G1.goods_id as G1_id")
->leftJoin("goods as G1", "G1.goods_id", "=", "T2.id")
->get();
dd($request);
关联模型
//创建模型
php artisan make:model Home/Goods
//定义一对一
class Goods extends Model
{
//如果不指定test2, 会按类名自动指定test2s, 自动加个s
protected $table = "goods";
//默认会操作表的created_at 和 updated_at 两个字段, 如果表中没有这两个字段则设置为 false;
public $timestamps = false;
public function test2(){
return $this->hasOne("App\Home\Test2", 'id', 'goods_id');
}
}
//使用一对一
public function index(Request $request)
{
$result = Goods::get();
foreach ($result as $key => $value){
if($value->test2){
var_dump($value->test2->name);
}
}
}
//定义一对多
public function test2(){
return $this->hasMany("App\Home\Test2", 'age', 'goods_id');
}
//使用一对多
public function index(Request $request)
{
$result = Goods::get();
foreach ($result as $key => $value){
if($value->test2){
foreach ($value->test2 as $key => $value){
var_dump($value->name);
}
}
}
}
//多对多
//第一个参数代表当前表要连接的另一个表, 第二个参数代表中间表, 第三个参数代表中间表和当前表建立连接的列名, 第四个参数代表中间表和另一个表建立连接的列名
public function test2(){
return $this->belongsToMany("App\Home\Test2", "relation", "goods_id", "test2_id");
}
//使用多对多
$result = Goods::get();
foreach ($result as $key => $value){
if($value->test2){
foreach ($value->test2 as $key => $value){
var_dump($value);
}
}
}