PHP LUMEN UPLOAD MEDIA

 

PHP LUMEN UPLOAD MEDIA

1.      Studi Kasus

Pada tutorial ini kita akan menambahkan fitur user profile. User profile ini digunakan untuk menyimpan data profil user. User dan Profile mempunyai hubungan One-to-one Relationship. Oleh karena itu kita harus membikin tabel baru dengan nama profiles. Dibawah ini adalah kolom-kolom yang harus ada di table profiles:

1)       id → increment id

2)       user_id → foreign key untuk menghubungkan dengan tabel users

3)       first_name → nama depan

4)       last_name → nama belakang

5)       summary → ringkasan profile

6)       image → image profile

 

2.      Membuat Table profiles

Untuk membuat table profiles, mari kita ikuti langkah-langkah berikut ini:

1)       Membuat database migration dengan menjalankan command dibawah ini pada terminal:

php artisan make:migration create_profiles_table

2)       Buka file database/migrations/...create_profiles_table.php, dan tambah code seperti dibawah ini

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();

});

3)       Jalankan command dibawah ini pada terminal: php artisan migrate

 

3.      Membuat Model Profile

Untuk membuat model user, ikuti langkah-langkah dibawah ini:

1.     Buat file baru dengan nama app/Models/Profile.php, codenya seperti dibawah ini.

protected $fillable = array(

    'user_id''first_name''last_name''summary''image'

);

 

public $timestamps = true;

 

public function user()

{

    return $this->belongsTo('app\User');

}

 

4.      Endpoint

Untuk fitur user profile kita akan menambahkan beberapa endpoint, yakni seperti ini:

Method (HTTP Verbs)

Endpoint

Description

Authenticated?

POST

/profiles

Untuk menambahkan dan mengupdate profile

Yes


 

GET

/profile/{userId}

Untuk menampilkan profile

No

GET

/profiles/image/{ima geName}

Untuk menampilkan image

No

 

5.      Membuat Fungsi Create dan Update Profile

Untuk membuat fungsi create dan update profile, mari kita ikuti langkah-langkah dibawah ini.

1)       Buka file routes/web.php, tambahkan code dibawah ini.

$router->group(['middleware' => ['auth']], function($router){

    $router->get('/posts''PostsController@index');

    $router->post('/posts''PostsController@store');

    $router->get('/posts/{id}''PostsController@show');

    $router->put('/posts/{id}''PostsController@update');

    $router->delete('/posts/{id}''PostsController@destroy');

    

    // Route Create Profiles

    $router->post('/profiles''ProfilesController@store');

    

});

2)       Buat file baru app/Http/Controllers/ProfilesController.php, code nya seperti dibawah ini.

public function store(Request $req)

{

    $input = $req->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 = $req->input('first_name');

    $profile->last_name = $req->input('last_name');

    $profile->summary = $req->input('summary');

 

    if ($req->hasFile('image')) {

        $firstName = str_replace(' ''_'$req->input('first_name'));

        $lastName = str_replace(' ''_'$req->input('last_name'));

 

        $imageName = Auth::user()->id . '_' . $firstName . '_' . $lastName;

        $req->file('image')->move(storage_path('uploads/image_profile'), $imageName);

 

        $current_image_path = storage_path('avatar') . '/' . $profile->image;

 

        if (file_exists($current_image_path)) {

            unlink($current_image_path);

        }

 

        $profile->image = $imageName;

    }

 

    $profile->save();

 

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

}

3)       Test fungsi create or update profiles menggunakan postman.


1.      Membuat Fungsi Get Profile

Untuk membuat fungsi get profile, mari kita ikuti langkah-langkah dibawah ini.

1)       Buka file routes/web.php, tambahkan code dibawah ini, simpan di paling bawah.

$router->get('/profile/{userId}''ProfilesController@show');

$router->get('/profile/image/{imageName}''ProfilesController@image');

2)       Buat file baru app/Http/Controllers/ProfilesController.php, tambahkan function show, code nya seperti dibawah ini.

public function show($userId)

{

    $profile = Profile::where('user_id'$userId)->first();

 

    if (! $profile){

        abort(400);

    }

 

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

}

 

public function image($imageName)

{

    $imagePath = storage_path('uploads/image_profile'). '/' . $imageName;

    if (file_exists($imagePath)){

        $file = file_get_contents($imagePath);

        return response($file200)->header('Content-Type''image/jpeg');

    }

 

    return response()->json(array(

        "message" => "image not found"

    ), 401);

}

3)       Test fungsi get profiles menggunakan postman.


1.      Membuat Fungsi Get Image Profile

Untuk membuat fungsi get image profile, mari kita ikuti langkah-langkah dibawah ini.

1)       Buka file routes/web.php, tambahkan code dibawah ini.

$router->get('/profile/{userId}''ProfilesController@show');

$router->get('/profile/image/{imageName}''ProfilesController@image');

2)       Buat file baru app/Http/Controllers/ProfilesController.php, tambahkan fungsi image, code nya seperti dibawah ini.

public function show($userId)

    {

        $profile = Profile::where('user_id'$userId)->first();

 

        if (! $profile){

            abort(400);

        }

 

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

    }

 

    public function image($imageName)

    {

        $imagePath = storage_path('uploads/image_profile'). '/' . $imageName;

        if (file_exists($imagePath)){

            $file = file_get_contents($imagePath);

            return response($file200)->header('Content-Type''image/jpeg');

        }

 

        return response()->json(array(

            "message" => "image not found"

        ), 401);

    }

3)       Test fungsi get image profiles menggunakan postman. Kalau image nya tidak ada seperti ini.

4)       Test fungsi get image profiles menggunakan postman. Kalau image nya ada seperti ini.





Komentar

Postingan populer dari blog ini

KONSEP, KELEBIHAN, KEKURANGAN CONTAINERIZATION BERSERTA TEKNOLOGI DAN STUDI KASUS CONTAINERIZATION

Mengapa Harus Belajar Cloud Computing ?

Setting Up VM and Domain