两种获取参数并赋给默认值的方法
//方法一
$pagenum = isset($input['pagenum']) ? $input['pagenum'] : 10;
//方法二
$prjguid = $request->input('prjguid', '222');
合并MySQL查询的结果集
//concat 方法将给定的 数组 或集合值追加到集合的末尾:
$collection = collect(['John Doe']);
$concatenated = $collection->concat(['Jane Doe'])->concat(['name' => 'Johnny Doe']);
$concatenated->all();
// 结果为:['John Doe', 'Jane Doe', 'Johnny Doe']
PHP格式化时间
//获取核算截止日期,若无,默认赋给今天的时间
$endDate = isset($input['endDate'])?$input['endDate']:date("Y-m-d");
// 处理日期格式
$endDate = date('Y-m-d',strtotime($endDate));
PHP获取时间
//设定指定的时间
$paybackdate = date_create("1990-01-01 12:59:59");
//获取当前时间
$inputime = date("Y-m-d H:i:s");
laravel原生查询方式,多条件
public function GetRows($selects,$wheres)
{
$rows = Sysdbdata::select(DB::raw($selects))
->whereRaw($wheres)
->get();
}
//多条件查询时,调用原生查询
$getguids = $guidobj->GetRows("sysdbdata_guid", "fieldguid = $changevalue[sysdbcols_guid]
and sysdbrowguid = $sysdbrows_guid and dbguid = $sysdb_guid");
Eloquent 封装的几个判空的方法
$users = DB::table('users')->where('id',$id)->get();
if (!$users->isEmpty()) {
//不为空
}
if ($users->count()) {
//不为空
}
分页详解
//前台模板
<label class="form-control-label">每页显示数目</label>
<select class="form-control" id="perPage" name="perPage">
<option value="" ></option>
<option value="10" >10</option>
<option value="20" >20</option>
<option value="30" >30</option>
<option value="50" >50</option>
</select>
//前台js
$(document).ready(function() {
$('#perPage').change(function () {
var p1 = $(this).children('option:selected').val();
//这就是selected的值
location.href = "{{route('projects.index')}}?perPage=" + p1;
//向后台传参,刷新页面
document.cookie = "id=" + p1;
//将select选中的value写入cookie中
})
})
//主页初始化加载cookie中保存的刚刚select选中的值
<body onload="selectIndex();">
</body>
<script>
//提取缓存下拉选框的值
function selectIndex(){
var id = 0;
var coosStr = document.cookie; //获取cookie中的数据
var coos=coosStr.split("; "); //多个值之间用; 分隔
for(var i=0;i<coos.length;i++){ //获取select写入的id
var coo=coos[i].split("=");
if("id" == coo[0]){
id=coo[1];
}
}
$("#perPage").val(id);
}
</script>
//后台,UIsever层
public function index()
{
$obj = new ProjectsBll();
$perPage = Input::get('perPage');
$Projectss = $obj->index($perPage);
}
//数据访问层
public function index($perPage)
{
$Projectss=Projects::paginate($perPage); //分页数量
$Projectss->withPath("?perPage=$perPage"); //自定义分页链接的URL
return $Projectss;
}
构建多表查询器
$rows = DB::table('tbl_readrec') //表名
->join('tbl_task', 'tbl_task.task_id', '=', 'tbl_readrec.targetid')
//内连接查询另一个关联表
->select('tbl_readrec.*', 'tbl_task.*')
//选择一起返回的属性字段
->where('tbl_readrec.userid', '=', $userid) //另加筛选条件
->where('tbl_readrec.type', '=', 'task') //另加筛选条件
->get();
//输出两个表的数据,符合条件的自动组合,成为一个子集,非常人性化!!!
参考例子:https://laravelacademy.org/post/920.html
向查询结果集的每个子集中加入新字段属性及其值
$obj2 = new ReadrecDal(); //new一个对象
$readrecs = $obj2->GetRows('*','type="alert"'); //传入sql语句,返回查询结果集
foreach ($Alertss as $Alert)
{
foreach ($readrecs as $readrec)
{
if($readrec->targetid == $Alert->alert_id)
{
$Alert["readrec"] = $readrec->isread;
//遍历结果集,凡是符合条件的结果子集,在其中加入新属性字段及其值
}
}
}
合并查询不同表的结果集
$get = new classtest();
$classes = $get->getclass(); //查询课程表
$a = new classfile();
$aa = $a->getfile(1); //查询文件表
foreach ($aa as $aaa)
{
$bb = $classes->push($aaa); //push()方法附加数据项到集合结尾
}
echo $bb; //输出两个表的查询结果集
toArray()
toArray
方法将集合转化为一个原生的 PHP 数组。如果集合的值是 Eloquent 模型,该模型也会被转化为数组:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
toJson()
toJson
方法将集合转化为 JSON:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toJson();
// '{"name":"Desk","price":200}'
laravel各种路径的获取方法
app_path函数返回app目录的绝对路径:
$path = app_path();
你还可以使用app_path函数为相对于app目录的给定文件生成绝对路径:
$path = app_path('Http/Controllers/Controller.php');
base_path()
base_path函数返回项目根目录的绝对路径:
$path = base_path();
你还可以使用base_path函数为相对于应用目录的给定文件生成绝对路径:
$path = base_path('vendor/bin');
config_path()
config_path函数返回应用配置目录的绝对路径:
$path = config_path();
database_path()
database_path函数返回应用数据库目录的绝对路径:
$path = database_path();
public_path()
public_path函数返回public目录的绝对路径:
$path = public_path();
storage_path()
storage_path函数返回storage目录的绝对路径:
$path = storage_path();
还可以使用storage_path函数生成相对于storage目录的给定文件的绝对路径:
$path = storage_path('app/file.txt');
获取laravel项目的路径的内置帮助函数基本都在这了
查询出的数组按照规定字段进行排序:
$courses = Course::orderBy('course_id','ASC')->get();
//ASC从小到大
//DESC从大到小
return view('course',['courses' => $courses]);
产生的SQL语句为:
SELECT * FROM `course` ORDER BY ` course_id ` ASC
路由种类
//空白
Route::get('/', function () {
return view('welcome');
});
//函数
Route::get('hello', function () {
return 'Hello, Welcome to LaravelAcademy.org';
});
Route::get('list', 'test@getList');
Route::post('add', 'test@add');
Route::get('addindex', function (){return view('add');});
路由重定向:
(1)web.php文件中
Route::redirect('/here', '/there', 301);
其中 here
表示原路由,there
表示重定向之后的路由,301
是一个 HTTP 状态码,用于标识重定向。
(2)App\Http\Controllers文件下重定向
//public function里
return redirect("http://localhost/renzhi/public/list");
//其中list在web.php文件里
Route::get('list', 'test@getList');
CSRF 保护
在 routes/web.php
路由文件中所有请求方式为 PUT
、POST
或 DELETE
的路由对应的 HTML 表单都必须包含一个 CSRF 令牌字段,否则,请求会被拒绝。
<form action="{{ URL('add') }}" method="post">
{{ csrf_field() }}
姓名:<input type="text" name="name" value="" />
</form>
数据库连接步骤:
(1)www\renzhi\config\database.php文件中应修改
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'user'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
(2)www\renzhi\.env文件中
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=user
DB_USERNAME=root
DB_PASSWORD=null
Eloquent ORM模型
(1)在www\renzhi\app\Model目录下创建“类同名”模型文件,contact文件内容有:
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019/2/24
* Time: 19:41
*/
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
/**
* 关联到模型的数据表
*
* @var string
*/
protected $table = "user";
/**
* 模型默认主键名为id,so修改主键名
*
* @var string
*/
protected $primaryKey = "user_id";
/**
* 使用批量赋值的属性(白名单)
*
* @var array
*/
protected $fillable = [
'user_id',
'name',
'nickname',
'gender',
'introduction',
'birthday',
'birthplace',
'id_card',
'address',
'school',
'education'
];
/**
* 表明模型是否应该被打上时间戳
*
* @var bool
*/
public $timestamps = false;
}
(2)在www\renzhi\app\Http\Controllers\test.php文件中存放写好的服务
其中包含对数据库的增删改查服务
<?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019/2/23
* Time: 10:08
*/
namespace App\Http\Controllers;
use App\Model\Contact;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class test extends Controller
{
//查询列表
public function getList()
{
$users = Contact::all();
return view('user', ['users' => $users]);
}
//更新列表页
public function updateindex()
{
$user_id = Input::get("user_id");
$users = Contact::where('user_id', $user_id)->get();
return view('update', ['users' => $users]);
}
//批量赋值更新操作
public function update(Contact $contact, Request $request)
{
$user_id = Input::get("user_id");
$user = Contact::find($user_id);
$user->update($request->all());
$user->save();
return redirect("http://localhost/renzhi/public/list");
}
//单属性赋值更新
public function update()
{
$user_id = Input::get("user_id");
$name = Input::get("name");
$nickname = Input::get("nickname");
$gender = Input::get("gender");
$introduction = Input::get("introduction");
$birthday = Input::get("birthday");
$birthplace = Input::get("birthplace");
$id_card = Input::get("id_card");
$address = Input::get("address");
$school = Input::get("school");
$education = Input::get("education");
$user = Contact::find($user_id);
$user->update(['name' => $name,
'nickname' => $nickname,
'gender' => $gender,
'introduction' => $introduction,
'birthday' => $birthday,
'birthplace' => $birthplace,
'id_card' => $id_card,
'address' => $address,
'school' => $school,
'education' => $education]);
return redirect("http://localhost/renzhi/public/list");
}
//添加列表
public function add()
{
$name = Input::get("name");
$nickname = Input::get("nickname");
$gender = Input::get("gender");
$introduction = Input::get("introduction");
$birthday = Input::get("birthday");
$birthplace = Input::get("birthplace");
$id_card = Input::get("id_card");
$address = Input::get("address");
$school = Input::get("school");
$education = Input::get("education");
$users = Contact::all();
foreach ($users as $users_id)
{
$user_id = $users_id->user_id;
}
$user = new Contact();
$user->user_id = $user_id + 1;
$user->name = $name;
$user->nickname = $nickname;
$user->gender = $gender;
$user->introduction = $introduction;
$user->birthday = $birthday;
$user->birthplace = $birthplace;
$user->id_card = $id_card;
$user->address = $address;
$user->school = $school;
$user->education = $education;
$user->save();
return redirect("http://localhost/renzhi/public/list");
}
//删除列表
public function dellist()
{
$user_id = Input::get("user_id");
Contact::where('user_id', $user_id)->delete();
echo "true";
}
}
前端
(1)lavarel框架下HTML文件中执行PHP语句
@foreach ($users as $user)
<input type="hidden" name="user_id" value="{{$user->user_id}}"/>
姓名:<input type="text" name="name" value="{{$user->name}}"/>
@endforeach
(2)前台传值到后台的几种方式
<a href="http://localhost/renzhi/public/updateindex?user_id={{$user->user_id}}" >
<button >点击修改</button>
</a>
<button onclick="deluser('del','{{$user->user_id}}')">点击删除</button>
<script>
function deluser(opt, opt_id) {
if (confirm("您确定删除该用户吗?")) {
$.ajax({
url: "http://localhost/renzhi/public/del",
type: "get",
data: {
"user_id": opt_id,
},
success: function (data) {
if (data === "true") {
alert('删除成功!');
location.reload();
}
}
})
}
}
</script>
<form action="Http://URL...." method="post">
{{ csrf_field() }}
姓名:<input type="text" name="name" value="" />
上传:<input type='submit' name='submit' value='submit'>
</form>
<script>
var id = $(".class").data("id")
location.href = "url?id=" + id;
</script>