Laravel教學 Part 1 - 新手入門

2018/05/30 posted in  Laravel comments

以下介紹初學Laravel需要知道的檔案結構和概念。

(基於Laravel v5.6)

Routing

  • Web Views: routes/web.php
  • API: routes/api.php
    • 預設的RouteServiceProvider會把這裡所有routes都自動prefix了api/

官方Routing Doc

Request & Response

Callback function

基本用法

Route::get('/', function () {
    return 'Hello World';
});

加上parameters

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

// Optional
Route::get('user/{name?}', function ($name = null) {
    return $name;
});

// Regex
Route::get('user/{id}/{name}', function ($id, $name) {
    //
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

View response

使用global view helper

Route::get('/', function () {
    return view('welcome');
});

預設會返回resources/views/{view_name}.blade.php

Blade

.blade.php代表它不是一般php檔,而是基於blade的template檔。

Blade是Laravel提供的一個Template Engine,提供方便的語法讓你render想要的資訊。

使用Blade Template Engine的好處

Redirect

Route::get('dashboard', function () {
    return redirect('home/dashboard');
});

HTTP Response

Route::get('home', function () {
    return response('Hello World', 200)
                  ->header('Content-Type', 'text/plain');
});

JSON

return response()->json([
    'name' => 'Abigail',
    'state' => 'CA'
]);

Controller

一般以上的callback不適合放一大堆logics,更多時候我們會使用controller來處理。

官方Controller Doc

基本用法

php artisan make:controller SomeController

新增於app/Http/Controllers/{}.php

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

Resource controller

提供基本CRUD的controller。

新增Controller

php artisan make:controller PhotoController --resource --model=Something

Define routes

Route::resource('photos', 'PhotoController');

// multiple
Route::resources([
    'photos' => 'PhotoController',
    'posts' => 'PostController'
]);

// Partial
Route::resource('photos', 'PhotoController')->only([
    'index', 'show'
]);

// Except
Route::resource('photos', 'PhotoController')->except([
    'create', 'store', 'update', 'destroy'
]);

Routes與對應Methods一覽

Route Method
GET /photos index
GET /photos/create create
POST /photos store
GET /photos/{photo} show
GET /photos/{photo}/edit edit
PUT /PATCH /photos/{photo} update
DELETE /photos/{photo} destroy

Model & Database

Migration

官方Migration Doc

一般Model都和Database脫不了關係,先了解一下DB migration怎麼做。

新增Model & DB Table

php artisan make:model Something
php artisan make:migration create_something_table
# 或
php artisan make:model Something
php artisan make:migration something --create=something
# 或
php artisan make:model Something --migration
# 或
php artisan make:model Something -m
  • create_xxx_table是convention的命名方法
  • --create=xxx設定要新增的table名稱
  • Model新增於app/Something.php
  • Migration新增於database/migrations
Default create

--create或名稱為create_xxx_table或使用-m的話,會自動幫你加入create table相關的code:

class Something extends Migration
{
    public function up()
    {
        Schema::create('something', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('something');
    }
}

更改Model

php artisan make:migration add_votes_to_users_table --table=users

設定--table=users會自動加入以下code:

public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }

執行Migration

php artisan migrate

(當然要先設置好Database)

Model

官方Model doc

初始狀態

class Something extends Model
{
    //
}

雖然甚麼也沒有,其實已經可以開始使用了。

Laravel的models有很多by convention地存在的東西,例如idcreated_atupdated_at等等。

取得instances

use App\Flight;

$flights = App\Flight::all();
foreach ($flights as $flight) {
    echo $flight->name;
}

$flights = App\Flight::where('active', 1)
               ->orderBy('name', 'desc')
               ->take(10)
               ->get();
               
$flight = App\Flight::find(1);

$count = App\Flight::where('active', 1)->count();

$max = App\Flight::where('active', 1)->max('price');

Available Methods

https://laravel.com/docs/5.6/eloquent-collections#available-methods

其他操作

https://laravel.com/docs/5.6/eloquent#inserting-and-updating-models

Event & Observer

https://laravel.com/docs/5.6/eloquent#events