Giter VIP home page Giter VIP logo

codeigniter4-media's Introduction

Codeigniter4-Media

Codeigniter package for to handle media upload file task (at least help a bit for my current job). My main goal on this package is codeigniter 4 have a library that be able to handle task such as organize file upload with minimial line of code

Installation

Composer

composer require rachyharkov/codeigniter4-media

Setup Model

just set your model like this

use CodeIgniter\Model;
use Rachyharkov\CodeigniterMedia\HasMedia;
use Rachyharkov\CodeigniterMedia\InteractsWithMedia;

class User extends Model implements HasMedia
{
    use InteractsWithMedia;

    // rest of codes
}

done

How to use?

Store single File

using name attribute of html input to let codeigniter4-media get the file, and add to specified collection (if no name entered, it will be using "default")

    $this->user_model->insert($data);
    $this->user_model->addMediaFromRequest('photo')->toMediaCollection('profile_photo');

Store single file - store thumbnail

It's useful if you want to store the thumbnail of the file, just add withThumbnail method after addMediaFromRequest method

    $this->user_model->insert($data);
    $this->user_model->addMediaFromRequest('photo')->withThumbnail()->toMediaCollection('profile_photo');

Store single File - with custom name

only use usingFileName method after addMediaFromRequest method, this will be useful if you want to rename the file before store it to database

    $this->user_model->insert($data);
    $this->user_model->addMediaFromRequest('photo')->usingFileName('data_'.random(20))->toMediaCollection('profile_photo');

Store Multi File - Different Name

store file from multi different request name (for example, you have 2 input file with different input file name attribute value, and you want to store it to same collection)

    $this->user_model->insert($data);
    $this->user_model->addMediaWithRequestCollectionMapping([
      'file_input_photo' => 'profile_photo_collection',
      'file_input_profile_cover' => 'profile_photo_collection'
    ])

Store Multi File - Same Name

This time using addMedia, make sure it's an file object (binary payload) to make addMedia accept value, in this example using multiple file input with same name attribute value

    $this->product_model->insert($data);
    $product_images = $this->request->getFiles();

    foreach ($product_images['photos'] as $key => $p) {
        $this->product_model->addMedia($p)->toMediaCollection('product_image');
    }

Get Single File - Metadata

$this->data['user'] = $this->user_model->where('id', $id)->first();
$this->data['user']->photo = $this->user_model->mediaOf($this->data['user']->id,'profile_photo')->getFirstMedia();

return view('user/edit', $data);

above will return null if no file meta information returned, handle it like this

    <img src="<?= $user->media ? $user->media->file_path.'/'.$user->media->file_name : $user->media ?>" alt="User Photo Profile">

Get Single File - Just URL

This is the example of how to assign new object to existing object (for example user object) with new property (photo) that contains the url of file

$this->data['user']->photo = $this->user_model->mediaOf($this->data['user']->id,'profile_photo')->getFirstMediaUrl();

return view('user/edit', $data);

It's possible to pass parameter with 'thumb' value to get the thumbnail of the file

    $media->getFirstMediaUrl('thumb');

Get All file of collection

Just return true on third parameter, if not specified, then you are trying to get the first file of collection indeed

    $data['user']->collection_of_photo_profile = $this->user_model->mediaOf($user_id, 'profile_photo', true);

    return view('user/edit', $data);

Delete file collection

    $this->user_model->delete($id); // just general delete method
    $this->user_model->clearMediaCollection('profile_photo', $id);

API Mode

create method in your controller just like this, set asTemp to true if you want to return the file metadata (this is useful if you want to show the file right after upload process completed, make sure to return it)

๐Ÿช„ Backend - Store File

public function api_upload()
{
    $user_id = $this->request->getVar('user_id');
    return $this->user_model->addMediaFromRequest('file')->toMediaCollection('profile_photo')->responseJson();
}

you will get this response

{
    status: "success",
    message: "File uploaded successfuly",
    data: {
        collection_name: "profile_photo"
        file_ext: "jpg"
        file_name: "default"
        file_path: "uploads/profile_photo"
        file_size: 62431
        file_type: "image/jpeg"
        model_id: "200090"
        model_type: "App\\Models\\User"
        orig_name: "20211128_165410.jpg"
        unique_name:  "1691502324_94b5e01970c97f5ac670.jpg"
    }
}

๐Ÿช„ Backend - Delete File

    public function api_delete()
    {
        return $this->user_model->clearMediaCollection(request()->getVar('temp_id'), 'profile_photo')->responseJson();
    }

You will get this response

    {
        status: "success",
        message: "File 1691502324_94b5e01970c97f5ac670.jpg deleted successfuly",
    }

Notes

Sorry if it looks completely messed up, i'm still develop an approach and functionality that might work like spatie media laravel.

Are you using this package and having a problem? feel free to open an issue.

and please, don't implement it with production yet, let me feel the pain first then u can use it after

License

MIT License

Contributing

You can contribute to this package by discovering bugs and opening issues. If you want to contribute code, please create a pull request. But you need to test it first using the demo project Here

codeigniter4-media's People

Contributors

rachyharkov avatar

Stargazers

 avatar  avatar

Watchers

 avatar

codeigniter4-media's Issues

Suggestions

  1. Simplified folder structure, ex: public > uploads > collection_name (remove temp folder)
  2. Add feature to define extention file type
  3. Change file name into: real_name+timestamp
  4. Add empty index.html with: Directory access is forbidden.

Multi File adding

this lib need to have multi file adding from multiple file input requests

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.