Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to Store Array in Database Laravel

How to Store Array in Database Laravel ?

Aman Jain, July 29, 2022March 16, 2024

In this article we will learn to Store Array in Database Laravel. Sometime in our application we have some raw information which we only want to store in our database and later on wanted to show back again. These type of information or data is only used for to keep track of records and not for any search purpose. So if the data is large and in form of array then we can store it in single column of database by serializing the array and cast it into string.

Array serialize function is used to convert a value to a sequence of bits, so that it can be stored in a file, memory, database and also can transferred between the different networks.

This example will work any version of laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9.

So to serialize a array

<?php
$data = serialize(array("male", "female", "none"));
echo $data; //a:3:{i:0;s:4:"male";i:1;s:6:"female";i:2;s:4:"none";}
?>

and for unserialize

<?php
$data = unserialize(a:3:{i:0;s:4:"male";i:1;s:6:"female";i:2;s:4:"none";});
var_dump($data); //array("male", "female", "none")
?>

Let’s understand Store Array in Database Laravel with example

Step 1: Create a laravel project

First step is to create the Laravel project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel crud

Step 2: Configure database

Next step is to configure the database for our project, table and data. So open .env or if file not exist then rename .env.example file to .env file in root folder and change below details

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Model and Migration

If you have table and large data already then you can skip this step but if you are beginner and trying to implement autosuggestion then in this step we are creating a model and migration using artisan command

php artisan make:model User -m

Step 4 : Create a controller

Next, Create a controller and two methods one for view and another for search the suggestion as follow

php artisan make:controller UserController

Now, add the controller logic

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    function index(){
        return view("users.index");
    }
    function store(Request $request){

        $validator = Validator::make($request->all(), [
            'email' => 'required|email',   // required and email format validation
            'phone_number.*' => 'required|numeric|digits_between:9,15', // required and number field validation
            'username' => 'required',
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            
            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form

        }
        else
        {

          $User =  new \App\Models\User;
          $User->email = $request->email;
          $User->phone_number = serialize($request->phone_number);
          $User->username = $request->username;
          $User->save();
          return redirect()->route("users.index")
          ->with('success', 'You have successfully created the user.');
            //handle the form 
        }  
    }
}

Here we created two methods index for show the view and submit method for store the array in database.

Step 5 : Create the view

Now, create a view file named as resources/views/users/index.blade.php and put the follow code

<!DOCTYPE html>
<html>

<head>
  <title>Store Array in Database Laravel - readerstacks.com</title>

</head>

<body>
  <div class="container">

    <div class="panel panel-primary">
      <div class="panel-heading">
        <h2>Store Array in Database Laravel -readerstacks.com</h2>
      </div>
      <div class="panel-body">

      @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <form method="post" action="{{url('users/submit')}}" name="registerform">
             <div class="form-group">
                <label>Email</label>
                <input type="text" name="email" value="{{ old('email') }}" class="form-control" />
                @csrf
              </div>
              <div class="form-group">
                <label>Phone number</label>
                <input type="text" name="phone_number[]"  value="{{ old('phone_number[0]') }}" class="form-control" />
              </div>
              <div class="form-group">
                <label>Phone number</label>
                <input type="text" name="phone_number[]"  value="{{ old('phone_number[1]') }}" class="form-control" />
              </div>
              <div class="form-group">
                <label>Username</label>
                <input type="text" name="username"   value="{{ old('username') }}" class="form-control" [ />
              </div>
            
              <div class="form-group">
                <button class="btn btn-primary">Register</button>
              </div>
            </form>

      </div>
    </div>
  </div>
</body>

</html>

 

Now, here we created array of phone number so that we can store them in database as string with serialize.

Step 6 : Create Route

Last and final step is to create the route for our implementation

<?php

use Illuminate\Support\Facades\Route;

Route::get('/users',"\App\Http\Controllers\UserController@index")->name('users.index');
Route::post('/users/submit',"\App\Http\Controllers\UserController@store");

Screenshot:

Store Array in Database Laravel
Store Array in Database Laravel
Store Array in Database Laravel
Store Array in Database Laravel

Store and Fetch Array using Getter and Setter

we can also achieve this by accessor and mutator by createing it in model then we doesn’t need to serialize it in controller as follow

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    function setPhoneNumberAttribute($value){
        
        $this->attributes['phone_number'] = serialize($value);
    }
    function getPhoneNumberAttribute(){
        return unserialize($this->phone_number);
    }
}

Related

Php Laravel Laravel 9

Post navigation

Previous post
Next post

Related Posts

Php How to Implement JWT Auth in Laravel

How to Implement JWT Auth in Laravel 9 ?

May 31, 2022August 20, 2022

JWT (Json Web Token) is used to create the authentication between two parties client and server that means it creates a secure information transactions between two parties. In the process of php-open-source-saver/jwt-auth token it creates a token claims and generates a token behalf of these claims then it verify on…

Read More
Laravel Efficient and Secure Way to Write Raw Queries in Laravel

Efficient and Secure Way to Write Raw Queries in Laravel

July 1, 2024July 1, 2024

Laravel is a powerful and versatile PHP framework that simplifies many aspects of web development, including database interactions. While Laravel’s Eloquent ORM and query builder are incredibly useful, there are times when you need to write raw SQL queries for more complex operations. However, writing raw queries requires a careful…

Read More
Laravel Laravel 10 Image Upload with Preview Example

Laravel 10 Image Upload: A Comprehensive Tutorial

October 23, 2023March 16, 2024

Laravel 10, renowned for its efficiency and simplicity, offers a seamless solution for handling image uploads in web applications. In Laravel 10 Image Upload tutorial, we will guide you through the process of uploading and displaying images using the robust features of Laravel 10. Whether you are a beginner or…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version