laravel7-路由

虞展
2023-12-01

laravel7

环境准备

phpstudy_pro

​ 新版本的比旧版好用多了。我直接用新版本,下载安装非常简单,网上教程一大把。安装完成后再安装composer,window版的一路next下来就可以了,然后配置环境变量 如D:\phpstudy_pro\Extensions\php\php7.3.4nts

#更换国内阿里源 毕竟国外下载速度慢
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

laravel下载

##默认使用这种方法下载 laravel安装器下载可能有各种麻烦
D:\phpstudy_pro\WWW>composer create-project --prefer-dist laravel/laravel mylaravel
#部分结果
……
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAut
> @php artisan package:discover --ansi
Discovered Package: [32mfacade/ignition[39m
Discovered Package: [32mfideloper/proxy[39m
Discovered Package: [32mfruitcake/laravel-cors
Discovered Package: [32mlaravel/tinker[39m
Discovered Package: [32mnesbot/carbon[39m
Discovered Package: [32mnunomaduro/collision[3
[32mPackage manifest generated successfully.[3
43 packages you are using are looking for fundin
Use the `composer fund` command to find out more
> @php artisan key:generate --ansi
[32mApplication key set successfully.[39m

#这就下载完成了
#执行命令 然后打开一个网页看看 
D:\phpstudy_pro\WWW\mylaravel>php artisan serve
Laravel development server started: http://127.0.0.1:8000
[Sat Jun 27 16:22:49 2020] 127.0.0.1:52191 [200]: /favicon.ico
#在浏览器中输入 localhost:8000 就可以看到相应的首页了

正式篇

ROUTE

路由就是接受http请求的路径,并和程序交互的功能,也就是为访问url地址,所作的一些设置工作。

输入 php artisan serve命令 ,即可支持 localhost:8000内置的服务器

路由的定义文件在根目录下的rputes/web.php 中,可以看到welcom页面

路由提交

#直接访问 http://localhost:8000/index
Route::get('index', function () {
    return 'hello world';
});

::get()就是get提交

::post() ::put() ::delete是表单和ajax的提交方式

::any () 全部提交都可以只能提交响应

::match() 指定接受你的提交方式,用数组作为参数传递

Route::match(['get','post'],'match', function () {
    return 'hello laravel match';
});
#返回  hello laravel match

路由规则和闭包

在路由规则和闭包区域,可以设置传递路由参数

Route::get('/index/{id}', function ($id) {
    return 'hello laravel user id'.$id;
});
http://localhost:8000/index/5
#输出  hello laravel user id 5
#这里没有对id作限制所以也可以传递字符
http://localhost:8000/index/abc
#输出  hello laravel user id abc

控制器controller和路由进行匹配

php artisan make:controller TaskController
#在app/Http/Controller下生成TaskController
class TaskController extends Controller
{
    //
    public  function  index(){
        return 'task index';
    }
    public function read($id){
        return 'id:'.$id;
    }
}

#route/web.php
Route::get('/task', 'TaskController@index');
#http://localhost:8000/index
#输出  task index


Route::get('/task/read/{id}','TaskController@read');
#http://localhost:8000/read/10
#输出  id:10
#http://localhost:8000/read/abc
#输出  id:abc


#匹配数字 字符串出错
Route::get('/task/read/{id}','TaskController@read')->where('id','[0-9]+');
#http://localhost:8000/read/10
#输出  id:10
#http://localhost:8000/task/read/abc
#出错

Route::get('/task/read/{id}','TaskController@read')->where('id','[0-9]+')->where(['id'=>'[0-9]+','name'=>'[a-z]+']);
#http://localhost:8000/read/10
#输出  id:10
#http://localhost:8000/task/read/10/abc
#出错

//必须两个参数
Route::get('/task/read/{id}/{name}','TaskController@read')->where(['id'=>'[0-9]+','name'=>'[a-z]+']);
#http://localhost:8000/read/1
#输出  id:11
#http://localhost:8000/task/read/11/abc
#输出 id:11 因为没有接收name


Route::get('/task/read/{id}','TaskController@read');
#多个匹配url直接在provides的 RouteServiceProvider -》boot方法 里面设置
 public function boot()
    {
        //这里可以对所有url的id参数做过滤
       Route::pattern('id','[0-9]+');
        parent::boot();
    }
    
#解除全局约束 也就是解除上面的Route::pattern('id','[0-9]+');的约束
Route::get('/task/read/{id}','TaskController@read')->where('id','.*');

#转跳
Route::get('/task', 'TaskController@index');
Route::redirect('index','task');
#http://localhost:8000/index 转跳到http://localhost:8000/task
#输出 task index

#还是转跳带状态码  301转跳
Route::redirect('/index','task',301);
Route::get('/task','TaskController@index');

#直接带状态码转跳  301转跳
Route::get('/task', 'TaskController@index');
Route::permanentRedirect('index','task');

视图路由

使用路由视图,要先创建一个视图V

视图路由有三个参数, uri(必) 名称(必) 参数(选)

#参数 URI http://localhost:8000/task
#参数 view resource/views/task.blade,php
#参数 传参 {{$id}}
Route::view('task','task',['id'=>'[0-9]+','name'=>'[a-z]+']);
http://localhost:8000/task
#404 因为还没有建立view文件 task.blade.php
#resources/views 下面建立task.blade.php文件
#输出  task 视图


Route::get('task', function (){
    return view('task',['id'=>10])
});
#视图 task
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
    task 视图 {{$id}}
</body>
</html>
#输出  task 视图 10


#常用
#路由
Route::get('task','TaskController@index');
#控制器
return view('task',['id'=>10]);
#view task.blade.php
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
    task 视图 {{$id}}
</body>
</html>
#http://localhost:8000/task
#输出  task 视图 10

路由命名

#web.php
Route::get('task/url','TaskController@url');
#controller
public function  url(){
        return 'url';
    }
#http://localhost:8000/task/url
#输出url

#
Route::get('task/url','TaskController@url');
Route::get('task','TaskController@index')->name('abc');
#
 public  function  index(){
        //return 'task index';
        return  view('task',['id'=>10]);
    }
    public function  url(){
        $url = route('abc');
        return $url;
    }
#http://localhost:8000/task/url
#输出 http://localhost:8000/task
##解释 也就是!!Route::get('task','TaskController@index')->name('abc') !!命名为abc 在控制器里面用route函数接收

#重定向 route
Route::get('task/url','TaskController@url');
Route::get('task','TaskController@index')->name('task.index');
#controller task
public  function  index(){
        //return 'task index';
        return  view('task',['id'=>10]);
    }
    
    public function  url(){
        $url = route('task.index',['id'=>10]);
        //return $url;
        return redirect()->route('task.index',['id'=>10]);
    }
#view
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
    task 视图 {{$id}}
</body>
</html>
#http://localhost:8000/task/url
#输出  task 视图 11

#重定向 route
Route::get('task/url','TaskController@url');
Route::get('task','TaskController@index')->name('task.index');
#controller task
public  function  index(){
        //return 'task index';
        return  view('task',['id'=>10]);
    }
    
    public function  url(){
        $url = route('task.index',['id'=>10],false);
        return $url;
    }

#输出  /task?id=11 也就是第三个参数位false 输出的uri

路由前缀

#路由前缀 不推荐 参数可以为空[]
Route::group(['prefix'=>'api'],function (){
    Route::get('index',function (){
        return 'index';
    });
    Route::get('task','TaskController@index');
});
#http://localhost:8000/api/indx
#输出 index

路由分组

##
Route::prefix('api')->group(function () {
    Route::get('index', function () {
        return  'api index';
    });
    Route::get('task','TaskController@index');
});
#http://localhost:8000/api/task
#输出 task 视图 10

子域名路由

Route::domain('127.0.0.1')->group(function (){
    Route::get('index',function (){
        return 'index';
    });
    Route::get('task','TaskController@index');
});
#http://localhost:8000/index 访问无效
#http://localhost:8000/task 访问无效
#只在 http://127.0.0.1:8000 访问有效=>laravel首页
#http://127.0.0.1:8000/index => index

子命名空间

Route::namespace('Admin')->group(function (){
    Route::get('index',function (){
        return 'index';
    });
    Route::get('task','TaskController@index');
    Route::get('manage','ManageController@index');
});
#http://localhost:8000/index 无法访问 404
#http://localhost:8000/task 无法访问 404
#admin/MangeController
public function index(){

        return  'manage';
    }
#http://localhost:8000/manage  => magage

fallback路由

#没有路由匹配 fallback 路由是一个覆盖默认 404 页面并引入其他逻辑的方法
Route::fallback(function (){
    return redirect('/');
});
#路由不正确 转跳到index 里面可以转跳到其他页面进行处理

Route::fallback(function (){
    return '404';
});
#路由不正确 转跳到index

当前路由信息

Route::get('index',function (){
    dump(Route::current());
});
#大数组 
Illuminate\Routing\Route {#203 ▼
  +uri: "index"
  +methods: array:2 [▶]
  +action: array:5 [▶]
  +isFallback: false
  +controller: null
  +defaults: []
  +wheres: array:1 [▶]
  +parameters: []
  +parameterNames: []
  #originalParameters: []
  #lockSeconds: null
  #waitSeconds: null
  +computedMiddleware: array:1 [▶]
  +compiled: Symfony\Component\Routing\CompiledRoute {#231 ▶}
  #router: Illuminate\Routing\Router {#26 ▶}
  #container: Illuminate\Foundation\Application {#2 ▶}
  #bindingFields: []
}

Route::get('index',function (){
    return Route::currentRouteName();
})-->name('loaction.index');
#http://127.0.0.1:8000/index =>   loaction.index



Route::get('task','TaskController@index');
#因为web.php 用的是 Illuminate\Support\Facades\Route;
#选择 Route::currentRouteAction();
 public  function  index(){
        //return 'task index';
        echo Route::currentRouteAction();
        //return  view('task',['id'=>10]);
    }
#http://127.0.0.1:8000/task =》 App\Http\Controllers\TaskController@index task 视图 10


响应设置

1 所有路由和控制器处理完业务逻辑之后都会返回一个发送到用户浏览器的响应 return

#字符会直接输出 数组输出json格式,本身是Response对象
return 'index';  # index

return [1,2,3];  # [1,2,3] json格式
return response([1,2,3]); # [1,2,3] json格式
return response()->json([1,2,3]); # [1,2,3] json格式


return response([1,2,3],201); # [1,2,3] json格式 201

return response('<b>index</b>')->header('Content-Type', 'text/html') #=》index

return response('<b>index</b>')->header('Content-Type', 'text/explain');#文本模 <b>index</b>
return response()->view('task', ['id'=>10], 200)->header('Content-Type', 'text/explain'); #文本模式
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>Document</title>
</head>
<body>
task 视图 10
</body>
</html>

return response('<b>index</b>')->header('Content-Type', 'text/html');#=》 task 视图 10

资源路由

#1
php artisan make:controller BlogController --resource
#查看资源路由
D:\phpstudy_pro\WWW\mylaravel>php artisan route:list
+--------+-----------+-------------------+---------------+---------------------------------------------+------------+
| Domain | Method    | URI               | Name          | Action                                      | Middleware |
+--------+-----------+-------------------+---------------+---------------------------------------------+------------+
|        | GET|HEAD  | api/user          |               | Closure                                     | api        |
|        |           |                   |               |                                             | auth:api   |
|        | GET|HEAD  | blogs             | blogs.index   | App\Http\Controllers\BlogController@index   | web        |
|        | POST      | blogs             | blogs.store   | App\Http\Controllers\BlogController@store   | web        |
|        | GET|HEAD  | blogs/create      | blogs.create  | App\Http\Controllers\BlogController@create  | web        |
|        | GET|HEAD  | blogs/{blog}      | blogs.show    | App\Http\Controllers\BlogController@show    | web        |
|        | PUT|PATCH | blogs/{blog}      | blogs.update  | App\Http\Controllers\BlogController@update  | web        |
|        | DELETE    | blogs/{blog}      | blogs.destroy | App\Http\Controllers\BlogController@destroy | web        |
|        | GET|HEAD  | blogs/{blog}/edit | blogs.edit    | App\Http\Controllers\BlogController@edit    | web        |
+--------+-----------+-------------------+---------------+---------------------------------------------+------------+
php artisan route:list
//单个资源路由
Route::resource('blogs','BlogController');

//批量资源路由
Route::resources(['blogs'=>'BlogController']);
//只能index show 访问
Route::resource('blogs','BlogController')->only(['index','show']);
//除了index show之外能访问
Route::resource('blogs','BlogController')->exept(['index','show']);

#api资源路由
php artisan make:controller CommentController --api
Route::apiResource('comments','CommentController');
D:\phpstudy_pro\WWW\mylaravel>php artisan route:list
+--------+-----------+--------------------+------------------+------------------------------------------------+------------+
| Domain | Method    | URI                | Name             | Action                                         | Middleware |
+--------+-----------+--------------------+------------------+------------------------------------------------+------------+
|        | GET|HEAD  | api/user           |                  | Closure                                        | api        |
|        |           |                    |                  |                                                | auth:api   |
|        | GET|HEAD  | comments           | comments.index   | App\Http\Controllers\CommentController@index   | web        |
|        | POST      | comments           | comments.store   | App\Http\Controllers\CommentController@store   | web        |
|        | GET|HEAD  | comments/{comment} | comments.show    | App\Http\Controllers\CommentController@show    | web        |
|        | PUT|PATCH | comments/{comment} | comments.update  | App\Http\Controllers\CommentController@update  | web        |
|        | DELETE    | comments/{comment} | comments.destroy | App\Http\Controllers\CommentController@destroy | web        |
+--------+-----------+--------------------+------------------+------------------------------------------------+------------+

#资源嵌套路由
Route::resources('blogs.comments','CommentController');
+-----------+--------------------------------------+------------------------+-----------------------------------------------
| Method    | URI                                  | Name                   | Action
+-----------+--------------------------------------+------------------------+-----------------------------------------------
| GET|HEAD  | api/user                             |                        | 
|           |                                      |                        |
| GET|HEAD  | blogs/{blog}/comments                | blogs.comments.index   | App\Http\Controllers\CommentController@index
| POST      | blogs/{blog}/comments                | blogs.comments.store   | App\Http\Controllers\CommentController@store
| GET|HEAD  | blogs/{blog}/comments/create         | blogs.comments.create  | App\Http\Controllers\CommentController@create
| GET|HEAD  | blogs/{blog}/comments/{comment}      | blogs.comments.show    | App\Http\Controllers\CommentController@show
| PUT|PATCH | blogs/{blog}/comments/{comment}      | blogs.comments.update  | App\Http\Controllers\CommentController@update
| DELETE    | blogs/{blog}/comments/{comment}      | blogs.comments.destroy | App\Http\Controllers\CommentController@destroy
| GET|HEAD  | blogs/{blog}/comments/{comment}/edit | blogs.comments.edit    | App\Http\Controllers\CommentController@edit
+-----------+--------------------------------------+------------------------+-----------------------------------------------
#
public function edit( $blog_id, $comment_id)
{
	return 'blog_id:'.$blog_id.'comen_id:'.$comment_id;
}
#http://localhost:8000/blogs/10/comments/15/edit      => blog_id:10comen_id:15

//优化资源嵌套 浅层
Route::resource('blogs.comments','CommentController')->shallow();
D:\phpstudy_pro\WWW\mylaravel>php artisan route:list
+-----------+------------------------------+------------------------+-------------------------------------+------------+
| Method    | URI                          | Name                   | Action                              | Middleware |
+-----------+------------------------------+------------------------+-----------------------------------------------+-----
| GET|HEAD  | comments/{comment}           | comments.show         | App\Http\Controllers\CommentController@show    | web |       |
| PUT|PATCH | comments/{comment}           | comments.update       | App\Http\Controllers\CommentController@update  | web |      |
| DELETE    | comments/{comment}           | comments.destroy      | App\Http\Controllers\CommentController@destroy | web |       |
| GET|HEAD  | comments/{comment}/edit      | comments.edit         | App\Http\Controllers\CommentController@edit    | web |
+-----------+------------------------------+------------------------+-----------------------------------------------+-----
public function edit( $comment_id)
{
    return 'comen_id:'.$comment_id;
}
#http://localhost:8000/comments/15/edit => comen_id:15


Route::resource('blogs.comments','CommentController')
    ->shallow()->name('index','b.c.i');
#or
Route::resource('blogs.comments','CommentController')
    ->shallow()->name([]'index'=>'b.c.i']);
public function edit( $id)
    {

        return route('b.c.i',['blog'=>10]);
       
    }
#http://localhost:8000/comments/15/edit =>http://localhost:8000/blogs/10/comments
   

Route::resource('blogs.comments','CommentController')
    ->shallow()->names(['index'=>'b.c.i'])->parameter('blogs','id');
public function edit( $id)
    {
        echo $id;
        return route('b.c.i',['id'=>$id]);
        //return 'comen_id:'.$comment_id;
    }
#http://localhost:8000/comments/35/edit =》35http://localhost:8000/blogs/35/comments



Route::resource('blogs.comments','CommentController')
    ->shallow()->names(['index'=>'b.c.i'])->parameters([
       'blogs'=>'id',
        'comments'=>'cid'
    ]);
|        | GET|HEAD  | blogs/{id}/comments        | b.c.i                 | App\Http\Controllers\CommentController@index   | web
   |
|        | POST      | blogs/{id}/comments        | blogs.comments.store  | App\Http\Controllers\CommentController@store   | web
   |
|        | GET|HEAD  | blogs/{id}/comments/create | blogs.comments.create | App\Http\Controllers\CommentController@create  | web
   |
|        | GET|HEAD  | comments/{cid}             | comments.show         | App\Http\Controllers\CommentController@show    | web
   |
|        | PUT|PATCH | comments/{cid}             | comments.update       | App\Http\Controllers\CommentController@update  | web
   |
|        | DELETE    | comments/{cid}             | comments.destroy      | App\Http\Controllers\CommentController@destroy | web
   |
|        | GET|HEAD  | comments/{cid}/edit        | comments.edit         | App\Http\Controllers\CommentController@edit    | web
   |

public function show($cid)
    {
        //
        return 'show id:'.$cid;
    }
    
#http://localhost:8000/comments/5   =》show id:5
   
 类似资料: