How to Store Multiple Select Values in Laravel? (ok)

https://www.itsolutionstuff.com/post/how-to-store-multiple-select-values-in-laravelexample.html

C:\xampp\htdocs\reset\database\migrations\2022_05_18_171017_create_posts_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('posts', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->text('description');
      $table->text('cat');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('posts');
  }
}

C:\xampp\htdocs\reset\app\Models\Post.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
  use HasFactory;
  protected $fillable = ['name', 'cat', 'description'];
  /**
   * Set the categories
   *
   */
  public function setCatAttribute($value) {
    $this->attributes['cat'] = json_encode($value);
  }
  /**
   * Get the categories
   *
   */
  public function getCatAttribute($value) {
    return $this->attributes['cat'] = json_decode($value);
  }
}

C:\xampp\htdocs\reset\routes\web.php

<?php
use App\Http\Controllers\HomeController;
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */
Route::get('/', function () {
  return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('postCreate', [PostController::class, 'postCreate']);
Route::post('postData', [PostController::class, 'postData'])->name('postData');

C:\xampp\htdocs\reset\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller {
  public function postCreate() {
    return view('post');
  }
  public function postData(Request $request) {
    $input = $request->all();
    Post::create($input);
    dd('Post created successfully.');
  }
}

C:\xampp\htdocs\reset\resources\views\post.blade.php

<html>
<head>
    <title>How to Store Multiple Select Values in Database using Laravel? - ItSolutionStuff.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
  <div class="row">
    <div class="col-md-8 offset-2 mt-5">
      <div class="card">
        <div class="card-header bg-info">
          <h6 class="text-white">How to Store Multiple Select Values in Database using Laravel? - ItSolutionStuff.com</h6>
        </div>
        <div class="card-body">
          <form method="post" action="{{ route('postData') }}" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
              <label>Name</label>
              <input type="text" name="name" class="form-control"/>
            </div>  
            <div class="form-group">
              <label><strong>Description :</strong></label>
              <textarea class="ckeditor form-control" name="description"></textarea>
            </div>
            <div class="">
              <label><strong>Select Category :</strong></label><br/>
              <select class="form-control" name="cat[]" multiple="">
                <option value="php">PHP</option>
                <option value="react">React</option>
                <option value="jquery">JQuery</option>
                <option value="javascript">Javascript</option>
                <option value="angular">Angular</option>
                <option value="vue">Vue</option>
              </select>
            </div>
            <div class="text-center" style="margin-top: 10px;">
              <button type="submit" class="btn btn-success">Save</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>    
</body>
</html> 

How to Store Multiple Select Values in Laravel?

Sometime we need to store multi select dropdown values in database using laravel. we can take json data type or text data type of that field so we can json_encode our array and store it into database.

Here, i will give you very simple and step by step example that will explain you how to store multiple select values in laravel using Accessors & Mutators. so let's see bellow example and bellow preview:

Preview:

Step 1: Create Migration

Here, in this example you need to create posts table with name, description and cat column. cat column has text or json data type. as bellow created:

database/migrations/2020_06_13_102114_create_posts_table.php

<?php  use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;  class CreatePostsTable extends Migration{    /**     * Run the migrations.     *     * @return void     */    public function up()    {        Schema::create('posts', function (Blueprint $table) {            $table->id();            $table->string('name');            $table->text('description');            $table->text('cat');            $table->timestamps();        });    }      /**     * Reverse the migrations.     *     * @return void     */    public function down()    {        Schema::dropIfExists('posts');    }}

Now we can run migration using bellow command:

php artisan migrate

Step 2: Create Post Model

Here, we will create Post model with Accessors & Mutators, so when you store categories then it will make json_encode() and when you get then json_decode(). so let's see bellow code:

app/Post.php

<?php  namespace App;  use Illuminate\Database\Eloquent\Model;  class Post extends Model{    protected $fillable = ['name','cat','description'];      /**     * Set the categories     *     */    public function setCatAttribute($value)    {        $this->attributes['cat'] = json_encode($value);    }      /**     * Get the categories     *     */    public function getCatAttribute($value)    {        return $this->attributes['cat'] = json_decode($value);    }}

Read Also: How to create middleware for XSS protection in Laravel?

Step 3: Create Routes

Here, we will simple create two routes one get route to access view and another post route for store data into database. so let's add two routes:

routes/web.php

Route::get('postCreate','PostController@postCreate');Route::post('postData','PostController@postData')->name('postData');

Step 4: Create Controller

Here, we will simple create PostController with two method that assign with route. so let's add two routes:

app/Http/Controllers/PostController.php

<?php  namespace App\Http\Controllers;  use Illuminate\Http\Request;use App\Post;  class PostController extends Controller{    public function postCreate()    {        return view('post');    }      public function postData(Request $request)    {        $input = $request->all();          Post::create($input);          dd('Post created successfully.');    }}

Step 5: Create Blade File

In this step, we will create blade file post.blade.php file there we added form code with multi select dropdown box. so let's put bellow code:

resources/views/post.blade.php

<html><head>    <title>How to Store Multiple Select Values in Database using Laravel? - ItSolutionStuff.com</title>    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"></head><body>    <div class="container">        <div class="row">            <div class="col-md-8 offset-2 mt-5">                <div class="card">                    <div class="card-header bg-info">                        <h6 class="text-white">How to Store Multiple Select Values in Database using Laravel? - ItSolutionStuff.com</h6>                    </div>                    <div class="card-body">                        <form method="post" action="{{ route('postData') }}" enctype="multipart/form-data">                            @csrf                            <div class="form-group">                                <label>Name</label>                                <input type="text" name="name" class="form-control"/>                            </div>                              <div class="form-group">                                <label><strong>Description :</strong></label>                                <textarea class="ckeditor form-control" name="description"></textarea>                            </div>                            <div class="">                                <label><strong>Select Category :</strong></label><br/>                                <select class="form-control" name="cat[]" multiple="">                                  <option value="php">PHP</option>                                  <option value="react">React</option>                                  <option value="jquery">JQuery</option>                                  <option value="javascript">Javascript</option>                                  <option value="angular">Angular</option>                                  <option value="vue">Vue</option>                                </select>                            </div>                                                          <div class="text-center" style="margin-top: 10px;">                                <button type="submit" class="btn btn-success">Save</button>                            </div>                        </form>                    </div>                </div>            </div>        </div>    </div>    </body>  </html> 

Now we are ready to app.

You can run application using bellow command:

Read Also: Laravel Multi Select Dropdown with Checkbox Example

php artisan serve

I hope it can help you...

Last updated