universal
universal

Reputation: 467

Laravel - Save multiple data to one column in database

I have a student form on Laravel 5.5 where users can add as many hobbies as they can. Each hobby has Title, Description & Image. I want to save all Hobbies. How can I save these information?

enter image description here

My view

<form action="/" method="post" enctype="multipart/form-data" files="true">
<input name="feat[]" type="text" placeholder="Feat 1">
<textarea name="feat_desc[]" placeholder="Feat 1 Desc">
<input type="file" name="feat_img[]">

<input name="feat2" type="text" placeholder="Feat 2">
<textarea name="feat2desc" placeholder="Feat 2 Desc">
<input type="file" name="feat2img">

<button>Add New Hobby</button>

JQuery for dynamic fields

$('#add-form').click(function() {
   i++;
    $('#add-me').append(

            '<input id="quantity" type="text" name="feat[]">'
            '<textarea name="feat_desc[]">'
            '<input type="file" name="feat_img[]">'
    );

});

My Controller:

public function create($Request $requst, Student $student)
$posts = Student::create([
        'name' => request('name'),
        'interests' => request('interests'),
        'hobbies' => json_encode(request('hobbies')),
        ]);

    return redirect ('/');

My database migration

{
    Schema::create('students', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('interests');
        $table->text('hobbies');
        $table->timestamps();
    });
}

Upvotes: 2

Views: 15883

Answers (2)

Vahid
Vahid

Reputation: 950

UPDATED ANSWER: I strongly recommend you to record each hobby in a separate table, because it is more clear and is better for search and indexing. you may have the second table hobbies like this:

Schema::create('student_hobbies', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('student_id')->unsigned();
    $table->string('title');
    $table->text('description');
    $table->string('path');
    $table->timestamps();
});

And then save each hobby in a new record with its student_id. in this case you can also save images into database instead of saving them on a separate storage. see this thread for more information.

Anyway if you decided to put all these info in a single field, do the following:

First of all, loop through the request, save files to a proper location with a unique name,and combine your hobbies Then save the hobbies to database using json_encode:

public function create($Request $requst, Student $student)
    $hobbies = [];
    $images = $request->file('feat_img');
    $descriptions = $request->feat_desc;
    foreach ($request->feat as $key => $title) {
        $filename = '';
        if (!empty($files[$key]) && $files[$key]->isValid()) {
            $filename = uniqid() . '.' . $files[$key]->getClientOriginalExtension();
            $files[$key]->move(storage_path('images'), $filename);
        }
        $hobbies[] = [
            'title' => $title,
            'desc' => $description[$key],
            'image' => $filename,
        ];
    }
    $posts = Student::create([
        'name' => request('name'),
        'interests' => request('interests'),
        'hobbies' => json_encode($hobbies),
    ]);
}

PREVIOUS ANSWER: You may save multiple data to a single column using CSV or JSON encoding form:

public function create($Request $requst, Student $student)
$posts = Student::create([
        'name' => request('name'),
        'interests' => request('interests'),
        'hobbies' => json_encode(request('hobbies')), // implode(',', request('hobbies'))
        ]);
return redirect ('/');

In the HTML, hobbies should look something like this:

<input name="hobbies[]" />
<input name="hobbies[]" />
...

Upvotes: 3

wahyzcrak
wahyzcrak

Reputation: 114

https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

It sounds like you may want use attribute casting to store the data as json that can be serialized and deserialized as array.

Upvotes: 1

Related Questions