控制器:Article.php
namespace App\Http\Controllers\Article;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class Article extends Controller
{
public function show()
{
//增加,2种方式皆可
$arr = DB::insert('insert into article(`title`,`img`,`newstext`) values(?,?,?)', ['盗梦空间', 'http....jpg', '这是一个盗梦的故事']); // ?占位符
$arr = DB::insert('insert into article(`title`,`img`,`newstext`) values(:title,:img,newstext)', ['盗梦空间', 'http....jpg', '这是一个盗梦的故事']);
//修改
$uppdate = DB::update('update article set `title`="喜乐街", `newstext`="这是一个在喜乐街的故事" where id=? ', [2]);
//删除
DB::delete('delete from article where id=?', [2]);
//查询,2种方式皆可
$res = DB::select('select * from article where id = ?', [1]); // ?为占位符
$res = DB::select('select * from article where id= :id', ['id'=>1]);
foreach($res as $val){
//这里数组内是对象
return view('index', ['index'=>$val]);
}
//获取全部
$args = DB::table('users')->get();
}
}
//
DB类之查询
DB::table("表名")->where("id","=",1)->get(); //这里=可省略
DB::table("表名")->where('id',1)->get();//结果同上
满足条件的全部获取:DB::table("表名")->where("id",">","1")->get();
满足条件的第一列获取:DB::table("表名")->where("id",">","1")->first();
满足条件的全部字段:DB::table("表名")->where("id",">","1")->lists("title");
路由
Route::get('/show', 'Article\Article@show');
模板引擎:index.blade.php
<p>{{$index->title}}</p>
<p><img src="{{$index->img}}"></p>
<p>{{$index->newstext}}</p>
必填参数,此方法最多
控制器:Article.php
class Article extends Controller
{
public function show($id)
{
$res = ['id'=>$id, 'title'=>'华为手机', 'price'=>5999];
return view('index', ['index'=>$res]);
}
}
路由
Route::get('/{id}.html', 'Article\Article@show'); //可实现类似京东的伪静态如:www.920930.com/2592652487.html
可选参数
控制器:Article.php
class Article extends Controller
{
public function show($id=3)//这是设置一个默认值,无值时默认为3
{
$res = ['id'=>$id, 'title'=>'华为手机', 'price'=>5999];
return view('index', ['index'=>$res]);
}
}
路由
Route::get('/itme/{id?}.html', 'Article\Article@show');
路由命名
Route::get('/{id}.html', 'Article\Article@show')->name('article-show');
//只要引用这个路由名article-show,就可以调用这个路由了
模板渲染
1、数据内外均为数组时
控制器:Article.php
class Article extends Controller
{
public function show()
{
//数据内外均为数组时
$res = [
['id'=>1, 'title'=>'华为手机', 'price'=>5999],
['id'=>2, 'title'=>'小米手机', 'price'=>2999],
['id'=>3, 'title'=>'魅族手机', 'price'=>1999]
];
return view('index', ['index'=>$res]);
}
}
模板渲染
@foreach($index as $item)
@if( $item['price'] < 2000 ) //注意这里的变量不能用{{}}包裹,否在报错
<p>{{$item['title']}},买得起</p>
@elseif( $item['price'] > 2000 && $item['price'] < 3000)
<p>{{$item['title']}},有点贵</p>
@else
<p>{{$item['title']}},太贵了</p>
@endif
@endforeach