Let's talk about Laravel8's routing and controller
This article brings you relevant knowledge about laravel, which mainly introduces issues related to routing and controllers, including routing groups, jumps to controllers, post routing, and Ajax Routing and other related content, let’s take a look at it below, I hope it will be helpful to everyone.
[Related recommendations: laravel video tutorial]
laravel access path is:
1) Routing—Controller— Page/Output
2) Routing—Anonymous Function—Page/Output
1. View all current routes
Enter the root directory of the current project and run cmd
or use IDE to automate Terminal with the shortcut key ALT F12
php artisan route:list
2. Various routes
In the routes/web.php file
My domain name is www.la.com, please choose according to your actual situation
1. Jump to the view
Route::get('/', function () { return view('welcome');});
View directory location: resources/views , which also stores HTML content. view()
is a helper function. view(‘welcome’) means jumping to the welcome.blade.php view, which is the welcome page we see when we start Laravel for the first time.
Write: www.la.com/ in the browser address bar, the running result is:
2. Directly output
Route::get('ok', function () { echo "hello world";});
3. Route with parameters
dump()
is laravel’s auxiliary function, used to print data
1) Single parameter
Route::get('show/{a}', function ($a) { dump($a);});
The browser runs http://www.la.com/show/1
Result: "1"
Note: It is a string
2) Multiple parameters
Route::get('show/{a}/{b}', function ($a,$b) { echo $a.','.$b;});
Browser running: http://www.la.com/show/1/hello
Result: 1,hello
4. Routing parameters added Restricted regular expression
Route::get('user/{name}/{age}', function ($name,$age) { echo $name.' '.$age; //直接输出 })->where('age','\d+')->where('name','[a-zA-Z]+');
The above restriction means that the age parameter can only accept numbers, and the name parameter can only accept uppercase and lowercase letters.
If the conditions are not met, the result is: 404 NOT FOUND
Run in browser: http://www.la.com/user/zhangsan/18
Result: zhangshan 18
5. Routing group
1) The first way to write Route::group(array('prefix'=>'user'),function(){});
Route::group(array('prefix'=>'user'),function(){ Route::get('/index', function () { echo 'index'; }); Route::get('/add', function () { echo 'add'; });});
Browser running:
- http://www.la.com/user/index
- http://www.la.com/user/add
Result:
- index
- add
2) The second way to write Route::prefix('user') ->group(function(){});
Route::prefix('user')->group(function(){ Route::get('/index', function () { echo 'index'; }); Route::get('/add', function () { echo 'add'; });});
6. Jump to the controller
1) Create the controller and write the method
to run in the project root directory
php artisan make:controller TestController
<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;class TestController extends Controller{ public function hello(){ echo "TestController的hello方法"; }}
2) Write routing
Add
use App\Http\Controllers\TestController;
at the beginning of config/web.php and then write routing
Route::get('/hello',[TestController::class,'hello']);//跳到控制器的方法
Browser running: http://www.la.com/hello
Result:
7.POST routing
in laravel In order to prevent csrf attacks, we must write the sentence @csrf in every post form. For details, you can click to read my other article
- We first enter
views/user Folder
Add aadd.blade.php
View
Code inside:
nbsp;html> <title>测试POST提交</title>
- Add route
use Illuminate\Http\Request;Route::prefix('user')->group(function(){ Route::get('/add', function () { return view('user.add'); }); Route::post('/insert', function (Request $request) { dump($request->all()); echo "post路由验证成功"; });});
view('user.add')
means the add view under the user folder in the resources/views directory. (resources/views is the default path)$request->all()
Get all request parametersdump()
Print data
- Test
First, entering http://www.la.com/user/insert directly will definitely not work and an error will be reported (The GET method is not supported for this route. Supported methods: POST .).
Postman enters http://www.la.com/user/insert post submission fails and returns 419 | Page Expired
So we first enter http:/ in the browser /www.la.com/user/add, fill in any name and submit
8.Ajax routing
The header should be added
Pass the token through js, here name="_token" you can choose any name
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name="_token
"]’).attr(‘content’)
},
nbsp;html> <meta> <title>CSRF</title> <meta><script></script><script> $.ajax({ url: "http://www.la.com/index",//本页面 type: "POST", data: { name:"名字" }, headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }, success: function (data) { console.log("200"); } });</script>
9.带别名的路由
别名路由就是给某一个路由起一个别名,直接使用使用原名可以访问路由,但直接使用别名不能访问这个路由,同时在其他页面调用别名可以访问这个路由。
Route::get('user/profile',function(){ return 'my url:'.route('profile');})->name('profile'); //创建一个路由 user/profile,这个路由的作用是返回路由 profile 的 RUL 地址,并给这个路由起一个别名 profile Route::get('redirect',function(){ return redirect()->route('profile'); }); //创建一个名为 redirect 的路由,这个路由的作用是跳转到路由 profile。
route() 生成完整的URL
redirect()->route(‘profile’); //重定向命名路由
在浏览器中运行 www.la.com/user/profile
结果:
在浏览器中运行www.la.com/profile
结果:404 NOT FOUND
在浏览器中运行www.la.com/redirect
结果:
10.命名空间路由
之前写的控制器 Controller 都直接写在 Http\Controllers 文件夹之中,但实际情况是控制器也会分类,比如与管理员相关的操作会在 Controllers 中,再建一个文件夹 Admin,然 后把所有关于管理员的控制器类都放在这个文件夹中。如果这样的话,就要添加名称空间。
- 创建控制器
方法一:使用phpartisan
php artisan make:controller Admin\IndexController
使用这种方法创建的控制器,自动加载名称空间,如下图所示
观察与之前创建控制器php artisan make:controller TestController
的区别
方法二:复制粘贴其他类
在Controllers文件夹下创建Admin文件夹,复制之前创建的控制器TestController,照着上图修改。
命名空间 namespace App\Http\Controllers\Admin;
添加类引用 use App\Http\Controllers\Controller;
- 控制器添加 index方法
public function index(){ return "Admin文件夹下的IndexController中的index方法";}
- 写路由
web.php文件
use App\Http\Controllers\Admin\IndexController;Route::group(['namespace'=>'Admin'],function(){ Route::get('admin',[IndexController::class,'index']);//管理员的主页 Route::get('admin/user',[IndexController::class,'index']);//管理员用户相关 Route::get('admin/goods',[IndexController::class,'index']);//商品相关});
浏览器输地址
http://www.la.com/admin
http://www.la.com/admin/user
http://www.la.com/admin/goods
结果都是一样
【相关推荐:laravel视频教程】
The above is the detailed content of Let's talk about Laravel8's routing and controller. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
