การใช้งาน Route เบื้องต้น

บทเรียนนี้ จะมาสอนถึงเรื่องการใช้งาน Route เบื้องต้น พูดถึง Route ก็เปรียบเสมือนตัวจัดการ url ที่ต้องการให้แสดงผล เริ่มกันเลยล่ะกัน
ให้ทำการเปิดไฟล์ app/Http/routes.php ขึ้นมา ข้างในจะมีสคริปตัวอย่าง ที่ทาง laravel ทิ้งไว้ให้
<?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', 'WelcomeController@index'); Route::get('home', 'HomeController@index'); Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => 'Auth\PasswordController', ]);
อธิบายจากตัวอย่าง
Route::get('/', 'WelcomeController@index');
คือการกำหนด Url เป็น htttp://www.yourweb.com หรือกำหนดหน้า Index ของเพจนั้นเอง โดยคำสั่งนี้จะเรียกใช้คำสั่งจาก WelcomeController method Index โดยการสั่งให้ Controller ที่อยู่ใน app/Http/Controllers/WelcomeController.php ทำงานนั้นเอง หากท่านติดตั้งไว้ที่ localhost ท่านสามารถทดสอบการแสดงผล ด้วยการพิมพ์ http://localhost/public/ ลงไปที่ช่อง Url ของ Browser
Route::get('home', 'HomeController@index');
ไม่ต่างอะไรกับ ตัวอย่างแรก หากต้องการทดสอบ ก็จะต้องพิมพ์ http://localhost/public/้home โดยคำสั่งนี้จะเรียกใช้คำสั่งจาก HomeController method Index โดยการสั่งให้ Controller ที่อยู่ใน app/Http/Controllers/HomeController.php ทำงานนั้งเอง
ส่วนตัวอย่างสุดท้าย
Route::controllers([ 'auth' => 'Auth\AuthController', 'password' => 'Auth\PasswordController', ]);
ตัวอย่างนี้ จะแตกต่างจากชาวบ้านชาวช่องเค้าหน่อย คือ เป็นการเรียกใช้ Controller โดยตรงครับ โดยจะเรียกใช้งาน ผ่าน AuthController ที่อยู่ใน app/Http/Controllers/Auth/PasswordController.php ครับ
ก็พอจะทราบหน้าที่ และวิธีการใช้งานของ Route กันบ้างแล้วนะครับ ขอจบบทเรียนนี้ไว้เท่านี้แล้วกันครับ
Comments
Comments are currently closed.
ของผมรันอยู่บน IIS และได้ทำการเพิ่ม URL Rewrite ใน web.config
ตรงบรรทัด ไม่รู้ถูกหรือเปล่าครับ แต่มันก็ทำงานได้ปกติ