[Laravel] Laravel Route

[Laravel] Laravel Route updated_at: 2024-01-30 17:58

Route

  • 외부의 요청을 받아서 컨트롤러에 전달하는 파트입니다.

Rount 파일

- routes
  - api.php
  - web.php
  ..........

기본형식

web.php을 예제로 처리

<?php
use Illuminate\Support\Facades\Route;

// /으로 들어오면 welcome 이라는 blade를 보여주는 가장간단한 형식
Route::get('/', function () { return view('welcome');});

Class를 바로 호출하는 방식

이 방법은 참조만 하시기를 바랍니다.

use App\Http\Controllers\Auth\AuthenticatedSessionController;

Route::get('login', [AuthenticatedSessionController::class, 'create'])->name('login');

group 설정

group으로 설정시 하위 내용들은 상위 그룹내용을 참조 하게 됩니다.

namespace 를 활용하는 방식

Route::group(['namespace' => 'App\Http\Controllers\Auth'], function () {
  Route::get('/register', 'RegisterController@create');
  // 실제 controller의 경로는 App\Http\Controllers\Auth\RegisterController 가 됩니다.
});

prefix

경로의 처음을 변경

Route::group(['prefix' => 'user'], function () {
  Route::get('/history', 'DashboardController@index')->name('dashboard');
  // 실제 경로는 Route::get('user/history')  와 동일

as

name 앞에 as 붙이기

Route::group([as' => 'user.'], function () {
  Route::get('/', 'DashboardController@index')->name('dashboard');
  // name('user.dashboard') 와 동일

middleware

Route::group(['middleware' => 'auth'], function () {
  Route::get('/', 'DashboardController@index')->name('dashboard');
  // ->name('dashboard')->middleware('auth'); 와 동일

Route Method

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Route::match(['get', 'post'], '/', function () {});
Route::any('/', function () {});

Route parameter

Route::get('/user/{id}', function ($id) {
  return 'User '.$id;
});

Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
  //
});

// 선택적 parameter
Route::get('/user/{name?}', function ($name = 'John') {
  return $name;
});

정규표현식 제약

Route::get('/user/{name}', function ($name) {
  //
})->where('name', '[A-Za-z]+');
Route::get('/user/{name}', function ($name) {
  //
})->where('name', '(trivia|saju)');

사용자 정의 Route 파일 설정하기

라라벨을 시작하면 기본적으로 routes 폴더에는 api.php, channels.php, console.php, web.php 라는 4개의 파일들이 생성됩니다.
이외에 서비스가 다양하고 커지다 보면 가령 web.php에서만 처리하기에는 복잡해지는데 별도로 route파일을 분리하면 수정 및 보기가 용이해집니다.

RouteServiceProvider 를 이용하는 방법

  • 새로운 route 파일(auth.php)을 작성 합니다.
  • App > Providers > RouteServiceProvider.php 을 오픈 하신 후 아래와 같이 현재 만든 라우터파일을 추가하시면 됩니다.
public function boot()
{
  $this->configureRateLimiting();

  $this->routes(function () {
    .....................

    Route::middleware('web')
      ->namespace($this->namespace)
      ->group(base_path('routes/auth.php'));
  });
}

기존 web.php에 바로 적용하기

위와 같은 방법이 번그롭다면 require를 사용하여 바로 적용하여도 됩니다.

  • web.php
..........
require __DIR__.'/auth.php';
평점을 남겨주세요
평점 : 4.5
총 투표수 : 2

질문 및 답글