Lumen Service App - Upload Media

 

Pada artikel kali ini kita akan melanjutkan membuat web service menggunakan PHP menggunakan framework Lumen dari Laravel. Pada kali ini kita akan menambahkan fitur upload media 

Pertama kita akan buat file migration untuk menambahkan table "profiles" , table ini berguna untuk menyimpan foto user dan informasi lainnya mengenai user. jalankan "php artisan make:migration create_profiles_table" pada command prompt 

Lalu buka file database/migrations/...create_profiles_table.php, dan ubah menjadi seperti dibawah ini

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProfilesTable extends Migration
{
    public function up()
    {
        Schema::create('profiles'function (Blueprint $table) {
            $table->bigIncrements('id');

            $table->integer('user_id')->index('user_id_foreign');
            $table->string('first_name'100);
            $table->string('last_name'100);
            $table->text('summary');
            $table->string('image'100)->nullable();
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('profiles');
    }
}

Jalankan command dibawah ini pada terminal: " php artisan migrate "

Membuat Model Profile

Selanjutnya kita akan membuat model untuk Profile , Buat file baru dengan nama app/Models/Profile.php, codenya seperti dibawah ini

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    protected $table        = 'profiles';
    protected $primaryKey   = 'id';
    protected $fillable = [       
        "user_id",    
        "first_name",     
        "last_name",      
        "summary",    
        "image",      
    ];

    public $timestamps = true;

    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }
}

Endpoint
Selanjutnya kita akan membuat endpoint untuk menampilkan Profile


Pertama kita akan menambahkan endpoint tersebut kedalam file "routes/web.php"


Setelah itu coba membuat ProfileController dan tambahkan buat seperti sintak di bawah ini

<?php

namespace App\Http\Controllers;

use App\Models\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ProfileController extends Controller
{
    public function store(Request $request)
    {
        $input              = $request->all();
        $validationRules    = [
            'first_name'     => 'required|min:2',
            'last_name'   => 'required|min:2',
            'summary'   => 'required|min:10',
        ];

        $validator          = \Validator::make($input$validationRules);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }
        
        $profile   = Profile::where('user_id'Auth::user()->id)->first();

        if (!$profile) {
            $profile = New Profile;
            $profile->user_id = Auth::user()->id;
        }

        $profile->first_name    = $request->input('first_name');
        $profile->last_name     = $request->input('last_name');
        $profile->summary       = $request->input('summary');

        if($request->hasFile('image')){
            $firstName  = str_replace(" ""_"$request->input('first_name'));
            $lastName   = str_replace(" ""_"$request->input('last_name'));

            $imageName  = Auth::user()->id."_".$firstName.'_'.$lastName;
            $current_image_path = storage_path('avatar').'/'.$profile->image;

            if (file_exists($current_image_path)) {
                unlink($current_image_path);
            }
            
            $request->file('image')->move(storage_path('avatar'), $imageName);

            $profile->image = $imageName;
        }

        $profile->save();

        return response()->json($profile200);

    }
}

Setelah itu coba pada postman



Selanjutnya kita akan menambahkan fungsi show pada ProfileController untuk mendapatkan data profile 

    public function show($userId)
    {
        $profile = Profile::where('user_id'$userId)->first();
        if (!$profile) {
            abort(404);
        }
        return response()->json($profile200);
    }

Setelah itu coba pada postman


dan terakhir kita akan menambahkan fungsi image pada ProfileController untuk mengambil Image

    public function image($imageName)
    {
        $imagePath = storage_path('avatar').'/'.$imageName;
        if (file_exists($imagePath)) {
            $file = file_get_contents($imagePath);
            return response($file,200)->header('Content-Type''image/jpeg');
        }

        return response()->json(array(
            "message"=>"Image not found"
        ), 401);
    }



Sekian tutorial mengenai Lumen Service App -  Upload Media, mohon maaf apabila banyak sekali kekurangan

Terima kasih




Next Post Previous Post
No Comment
Add Comment
comment url