Pavlo Zhukov
Pavlo Zhukov

Reputation: 3337

Convenient way to store related data in Laravel 5.5

I have next data structure:

There is user table users. Each user can have 4 types of files.

Is it possible to save it in table structure like this : files ?

id | user_id | type1 | type2 | type3 | type4

Also is it possible to use code similar to next?

$user->files($type, $value);

Upvotes: 0

Views: 48

Answers (1)

Pavlo Zhukov
Pavlo Zhukov

Reputation: 3337

I resolve this task in next way

migration_file.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ImplementFilesStorage extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->integer(['files_id'])->unsigned();
        });

        Schema::create('files', function (Blueprint $table) {
            $table->increments('id');
            $table->string('id_file')->nullable();
            $table->string('bill_file')->nullable();
            $table->string('card_back_file')->nullable();
            $table->string('card_front_file')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('manager_files');
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['files_id']);
        });
    }
}

User.php

class User extends EloquentUser {
    protected $table = 'users';
    public function files()
    {
        return $this->hasOne('App\File', 'files_id');
    }
}

File.php

class File extends Model
{
    protected $table = 'files';

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

    public function type($type, $filename = '')
    {
        $field_name = $type . '_file';
        if ($filename) {
            $this->{$field_name} = $filename;
        }

        return $this->{$field_name};
    }
}

And now for reading values I use $user->files->type($type_name) and for writing
$user->files->type($type_name, $stored_value).

Notice: to save changes in files table after all operations we need to call $user->files->save();.

If you have some notification about not convenient ORM usage please notify me.

P.S: actually I resolved quite harder task. Possibly a bit later I will post it on my blog and provide link here.

Upvotes: 1

Related Questions