Tutorial Rest Api Laravel Bahasa Indonesia

Demo programa

Prasyarat

  • Mempunyai sangkut-paut internet
  • PHP >= 7.4
  • Sudah terinstall composer
  • Sudah terinstall Terminal (CMD,Cmder, Git bash)
  • Virtual web server (XAMPP,Laragon , dll..)
  • Web browser (Google Chrome, Mozilla Firefox, Opera Web Browser, dll…)
  • Sudah terinstall database (MySQL,MariaDB, dll..)
  • Sudah membuat database dengan keunggulanlaravel_trans

Takhlik project laravel

Dalam artikel ini untuk instalasi Laravel menggunakan atau melalui composer berikut perintahnya:

        composer create-project laravel/laravel laravel-trans
      

Nama project yang dibuat yaitu laravel-trans

Konfigurasi env (environment)

Bentang file {projectName}\.env, dahulu atur value dari konfigurasi database

        DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_trans DB_USERNAME=root DB_PASSWORD=
      

masih di file .env tambahkan attribute baru seperti berikut:

        APP_API_URL=http://laravel-trans.test/jago merah/
      

Karena dalam artikel ini admin mewujudkan virtual host dengan jenama “laravel-trans.test”. Maka silahkan buat virtual host terlebih dahulu entah itu dengan tera yang seimbang (laravel-trans.test) maupun selisih. Sekiranya menjalankan project laravel via
php artisan serve
, maka sesuaikan dengan port yang diberikan. Contoh: http://127.0.0.1:8000 maka APP_API_URL=http://127.0.0.1:8000/api/. Minta baca diskusi (baca disini)
sekiranya menjalankan project laravel memperalat
php artisan serve

Install package laravel-translatable

Berikut perintah di terminal untuk install package laravel-translatable yang dibuat oleh astrotomic

        
          composer require astrotomic/laravel-translatable
      

Selepas itu bikin perintah berikut buat publish file konfigurasi dari package laravel-translatable

        php artisan vendor:publish --tag=translatable
      

Buka file {projectName}\config\translatable.php

Ganti value dari key berikut

        
          'locales' => [         'en',         'fr',         'es' => [             'MX', // mexican spanish             'CO', // colombian spanish         ],     ],
      

Menjadi

        
          'locales' => [         'en',         'id',     ],
      

Dalam kursus ini bahasa yang digunakan merupakan bahasa Inggris(en) dan bahasa Indonesia(id)

Menciptakan menjadikan migration

Berikut perintah bakal membentuk migration bagi tabel post

        php artisan make:migration create_posts_table
      

dan sesuaikan isi file dari
{projectName}\database\migrations\xxxx_xx_xx_xxxxxx_create_posts_table.php

        <?php  use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema;  class CreatePostsTable extends Migration {     public function up()     {         Schema::create('posts', function (Blueprint $table) {             $table->increments('id');             $table->string('author');             $table->timestamps();         });     }      public function down()     {         Schema::dropIfExists('posts');     } }
        
      

Lebih jauh berikut perintah bikin membuat migration lakukan tabel post translation

        php artisan make:migration create_post_translations
      

dan sesuaikan isi file dari
{projectName}\database\migrations\xxxx_xx_xx_xxxxxx_create_post_translations.php

        <?php  use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema;  class CreatePostTranslations extends Migration {      public function up()     {         Schema::create('post_translations', function (Blueprint $table) {             $table->increments('id');             $table->integer('post_id')->unsigned();             $table->string('locale')->index();             $table->string('title');             $table->text('content');             $table->unique(['post_id', 'locale']);             $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');         });     }      public function down()     {         Schema::dropIfExists('post_translations');     } }
        
      

Membuat lengkap

Membuat model Post

        php artisan make:model Post
      

{projectName}\app\Models\Post.php

        <?php  namespace App\Models;  use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model;  use Astrotomic\Translatable\Contracts\Translatable as TranslatableContract; use Astrotomic\Translatable\Translatable;  class Post extends Model implements TranslatableContract {     use HasFactory;     use Translatable;      public $translatedAttributes = ['title', 'content'];     protected $fillable = ['author']; }
        
      

Membuat sempurna PostTranslation

        php artisan make:model PostTranslation
      

{projectName}\app\Models\PostTranslation.php

        <?php  namespace App\Models;  use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model;  class PostTranslation extends Transendental {     use HasFactory;      public $timestamps = false;     protected $fillable = ['title', 'content']; }
        
      

Membuat seed data

        php artisan make:seeder PostTableSeeder
      

{projectName}\database\seeders\PostTableSeeder.php

        <?php  namespace Database\Seeders;  use App\Models\Post; use Illuminate\Database\Seeder;  class PostTableSeeder extends Seeder {     public function run()     {         $posts_1 = [             'author' => "ilmukita",             'id' => [                 'title' => "Halo marcapada",                 'content' => "Konten ini internal bahasa Indonesia"             ],             'en' => [                 'title' => "Hello world",                 'content' => "This content is in English"             ],         ];         $posts_2 = [             'author' => "Fauzi",             'id' => [                 'title' => "Ini adalah episode judul dari posting",                 'content' => "Ini adalah bagian konten dari posting"             ],             'en' => [                 'title' => "This is the title part of the post",                 'content' => "This is the content part of the post"             ],         ];          Post::create($posts_1);         Post::create($posts_2);     } }
        
      

{projectName}\database\seeders\DatabaseSeeder.php

        <?php  namespace Database\Seeders;  use Illuminate\Database\Seeder;  class DatabaseSeeder extends Seeder {     public function run()     {         $this->call([PostTableSeeder::class]);     } }
        
      

Mengerjakan migrate dan seed data

Berikut perintah buat migrate dan seed data secara bersamaan

        
          php artisan migrate --seed
      

Membuat controller

        php artisan make:controller web/HomeController
      

{projectName}\app\Http\Controllers\web\HomeController.php

        <?php  namespace App\Http\Controllers\web;  use App\Http\Controllers\Controller; use GuzzleHttp\Client;  class HomeController extends Controller {     public function index()     {         $endpoint = env('APP_API_URL') . app()->getLocale() . "/posts";         $client = new Client();         $response = $client->request('GET', $endpoint, [             'headers' => [                 'Accept' => "application/json"                 //any config             ]         ]);         return  json_decode($response->getBody());     } }
        
      
        
          php artisan make:controller jago merah/PostController
      

{projectName}\app\Http\Controllers\api\PostController.php

        <?php  namespace App\Http\Controllers\api;  use App\Http\Controllers\Controller; use App\Models\Post;  class PostController extends Controller {     public function index()     {         $posts = Post::withTranslation()->get();         return response()->json([             'gengsi' => 'SUCCESS',             'message' => 'Post successfully loaded',             'data' => $posts         ]);     } }
        
      

Membuat middleware

        
          php artisan make:middleware SetLocale
      

Berikut isi dari middleware SetLocale
{projectName}\app\Http\Middleware\SetLocale.php

        <?php  namespace App\Http\Middleware;  use Closure; use Illuminate\Http\Request;  class SetLocale {     public function handle(Request $request, Closure $next)     {         $locale = in_array($request->route('locale'), ['id', 'en']) ? $request->route('locale') : "en";         app()->setLocale($locale);         return $next($request);     } }
        
      

jangan lupa daftarkan middleware yang sudah lalu dibuat tersebut di
{projectName}\app\Http\Kernel.php

        protected $routeMiddleware = [      //any routeMiddleware ...     'setLocale' => \App\Http\Middleware\SetLocale::class ];
      

Konfigurasi route

{projectName}\routes\web.php

        <?php  use Illuminate\Support\Facades\Route;  Route::get('/', function () {     $locale = 'id'; //default     return redirect()->route('home.index', ['locale' => $locale]); });  Route::group([     'prefix' => '{locale}',     'where' => ['locale' => '[a-zA-Z]{2}'],     'middleware' => ['setLocale'] ], function () {     Route::get('/', [App\Http\Controllers\web\HomeController::class, 'index'])->name('home.index'); });
        
      

{projectName}\routes\jago merah.php

        <?php  use Illuminate\Support\Facades\Route;  Route::group([     'prefix' => '{locale}',     'where' => ['locale' => '[a-zA-Z]{2}'],     'middleware' => ['setLocale']     // with auth     // 'middleware' => ['setLocale', "auth:sanctum"] ], function () {     Route::get('/posts', [App\Http\Controllers\jago merah\PostController::class, 'index']); });
        
      

Uji coba

Source: http://ilmukita.org/laravel-8-multi-bahasa-rest-api/