Examples of PHP Laravel routing, middleware, database, etc.

Here are some common examples when using the Laravel framework:

1. Routes:


// Define the basic route
Route::get('/home', 'HomeController@index');

// route with parameters
Route::get('/user/{id}', 'UserController@show');

// 路由组
Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', 'DashboardController@index');
    Route::post('/user', 'UserController@store');
});
 

2. Middleware:


// 定义中间件
class AuthenticateMiddleware
{
    public function handle($request, $next)
    {
        if (!Auth::check()) {
            return redirect('/login');
        }
        return $next($request);
    }
}

// Use middleware in routing
Route::middleware(['auth'])->get('/dashboard', 'DashboardController@index');

// Global middleware
// Register middleware in the `$middleware` attribute of app/Http/Kernel.php file
protected $middleware = [
    \App\Http\Middleware\EncryptCookies::class,
    \App\Http\Middleware\ VerifyCsrfToken::class,
    \App\Http\Middleware\OtherMiddleware::class,
];
 

3. Database:


// query data
$users = DB::table('users')->get();

// Insert data
DB::table('users')->insert([
    'name' => 'John Doe',
    'email' => '[email protected]',
]);

// update data
DB::table('users')
    ->where('id', 1)
    ->update(['name' => 'Jane Doe']);

// Delete data
DB::table('users')->where('id', 1)->delete();
 

These examples cover common functionality in Laravel. Routing is used to define the URL routing rules of the application, middleware is used to process request filtering and operations, and database is used to perform database-related operations. Please note that these examples are for reference only and may need to be adjusted appropriately according to specific needs in actual use.

Supongo que te gusta

Origin blog.csdn.net/canduecho/article/details/131394989
Recomendado
Clasificación