วิธีการกำหนด Routing ใน Laravel Framework
Step 1 - ให้เข้าไปที่ route\web.php Step 2 - จะเห็นว่าได้มีการกำหนด routing '/' ผ่าน URL โดยให้แสดงผลที่หน้าแรก , และมีการคืนค่าไปที่หน้า welcome.blade.php ตัวอย่าง : Coding
โค้ด: เลือกทั้งหมด
Route::get('/', function () {
return view('welcome');
});
ผลลัพธ์ที่ได้ Step 3 - ที่นี้จะเป็นกำหนด Routing ให้วิ่งไปที่ทำงาน Controller และ Function , เพื่อให้การทำงานของ Coding ดูเป็นระเบียบมากขึ้น , หากต้องการกำหนด URL เป็นหน้าแรกของ index ให้ทำการตั้งชื่อ '/' , แล้วให้วิ่งไปที่ Controller_show_airport.php , แล้ววิ่งไปที่ Function index ตัวอย่าง : Coding
โค้ด: เลือกทั้งหมด
Route::get('/','Controller_show_airport@index');
โค้ด: เลือกทั้งหมด
public function index()
{
return view('showAirport');
}
การส่งค่า Parameter ผ่าน Routing
Step 1 - จะเป็นการส่งค่า id ผ่าน URL ไป , โดยมีเครื่องหมาย {} ในการส่งค่าไป , โดนให้เข้าไปทำงานที่ Controller_show_airport.php แล้ววิ่งไปที่ Functions test ตัวอย่าง : Coding
โค้ด: เลือกทั้งหมด
Route::get('/test_id/{id}', 'Controller_show_airport@test');
โค้ด: เลือกทั้งหมด
public function test($id)
{
echo "This is my ID".$id;
}
Routing Groups prefix
Step 1 - เป็นการกำหนด Routing โดยใช้ prefix มาเป็นตัวจัดการ , ในการที่เราไม่ต้องตั้งชื่อ Routing ซ้ำๆไปมา
ตัวอย่าง : Coding
โค้ด: เลือกทั้งหมด
Route::get('/showAirline','Controller_show_airline@create');
Route::get('/showAirline/{id}','Controller_show_airline@store');
Route::get('/showAirline/{id}','Controller_show_airline@update');
Route::get('/showAirline/{id}','Controller_show_airline@destroy');
ตัวอย่าง : Coding
โค้ด: เลือกทั้งหมด
Route::prefix('showAirline')->group(function () {
Route::get('','Controller_show_airline@create');
Route::get('{id}','Controller_show_airline@store');
Route::get('{id}','Controller_show_airline@update');
Route::get('{id}','Controller_show_airline@destroy');
});
Routing ใน Laravel นั้นจำเป็นอย่างมาก เพราะ ทุก Request เราต้องควบคุมผ่าน Routing นี้ , ซึ่งใช้งานไปอาจจะดูลำบาก แต่พอใช้งานได้ไปสักพัก จะทำให้รู้สึกว่ามีความสะดวกสบายในการใช้งานมากขึ้น , หากต้องการศึกบทเรียนจาก Laravel Framework เพิ่มเติม สามารถศึกษาได้จากบทเรียนนี้
แหล่งอ้างอิงข้อมูล
https://www.itoffside.com/laravel-ep5-routing/
https://laravel.com/docs/7.x/routing