illegal string offset 'name'.how to solve this error can anyone please tell me

Published 3 months ago by jhansi

http://www.awesomescreenshot.com/showImage?img_id=2303478 You can see error by going to above url. Democontroller.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Excel;

class DemoController extends Controller
{
    public function importExport()
    {
        return view('importExport');
    }
    public function downloadExcel(Request $request, $type)
    {
        $data = User::get()->toArray();
        return Excel::create('users', function($excel) use ($data) {
            $excel->sheet('mySheet', function($sheet) use ($data)
            {
                $sheet->fromArray($data);
            });
        })->download($type);
    }

    /**
     * Import file into database Code
     *
     * @var array
     */
    public function importExcel(Request $request)
    {

        if($request->hasFile('import_file')){
            $path = $request->file('import_file')->getRealPath();

            $data = Excel::load($path, function($reader) {})->get();

            if(!empty($data) && $data->count()){

                foreach ($data->toArray() as $key => $value) {
                    if(!empty($value)){
                        foreach ($value as $v) {        
                            $insert[] = ['name' => $v['name'], 'email' => $v['email'],'Team' => $v['Team'],'Vendor' => $v['Vendor'],'password'=>$v['password'];
                        }
                    }
                }

                
                if(!empty($insert)){
                    User::insert($insert);
                    return back()->with('success','Insert Record successfully.');
                }

            }

        }

        return back()->with('error','Please Check your file, Something is wrong there.');
    }

}

web.php

ute::get('importExport', [email protected]');
Route::get('downloadExcel/{type}', [email protected]');
Route::post('importExcel', [email protected]');

importExport.blade.php

<html lang="en">
<head>
    <title>Import - Export Laravel 5.3</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
</head>

<body>
<br/>
<br/>
    <div class="container">     
        <div class="panel panel-primary">
          <div class="panel-heading">
            <h3 class="panel-title" style="padding:12px 0px;font-size:25px;"><strong>Laravel 5.3 - import export csv or excel file into database example</strong></h3>
          </div>
          <div class="panel-body">

                @if ($message = Session::get('success'))
                    <div class="alert alert-success" role="alert">
                        {{ Session::get('success') }}
                    </div>
                @endif

                @if ($message = Session::get('error'))
                    <div class="alert alert-danger" role="alert">
                        {{ Session::get('error') }}
                    </div>
                @endif

                <h3>Import File Form:</h3>
                <form style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;" action="{{ URL::to('importExcel') }}" class="form-horizontal" method="post" enctype="multipart/form-data">

                    <input type="file" name="import_file" />
                    {{ csrf_field() }}
                    <br/>

                    <button class="btn btn-primary">Import CSV or Excel File</button>

                </form>
                <br/>

                
                <h3>Import File From Database:</h3>
                <div style="border: 4px solid #a1a1a1;margin-top: 15px;padding: 20px;">         
                    <a href="{{ url('downloadExcel/xls') }}"><button class="btn btn-success btn-lg">Download Excel xls</button></a>
                    <a href="{{ url('downloadExcel/xlsx') }}"><button class="btn btn-success btn-lg">Download Excel xlsx</button></a>
                    <a href="{{ url('downloadExcel/csv') }}"><button class="btn btn-success btn-lg">Download CSV</button></a>
                </div>

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

</body>

</html>
Best Answer (As Selected By jhansi)
Snapey

So what does the error show you?

Field password does not have a default value

SQL requires that you tell it a default value for the password. Either in the table configuration or by passing a password value on the insert.

SaeedPrez

This line is the problem,..

// bad
$insert[] = ['name' => $v['name'], 'email' => $v['email'],'Team' => $v['Team'],'Vendor' => $v['Vendor'],'password'=>$v['password'];

// good
$insert[] = ['name' => $v['name'], 'email' => $v['email'],'Team' => $v['Team'],'Vendor' => $v['Vendor'],'password'=>$v['password']];

// also good
array_push($insert, ['name' => $v['name'], 'email' => $v['email'],'Team' => $v['Team'],'Vendor' => $v['Vendor'],'password'=>$v['password']]);
jhansi

Yes,but it is the way to insert data (import) to my users table

SaeedPrez

@jhansi did this not solve your problem illegal string offset 'name' ?

jhansi

No it was not solved.same error occuring

SaeedPrez

Well, it's complaining that your array does not have the key/offset name. This can be caused even if only one of your arrays doesn't have that key.

So you need to check the data you're sending into the foreach loop.

jhansi

@SaeedPrez please explain me via example so that i can understand it clearly

SaeedPrez

@jhansi

Let's assume you have the following array..

$data = [
    ['name' => 'Saeed Prez',    'email' => [email protected]'],
    ['name' => 'John Doe',      'email' => [email protected]'],
    [                           'email' => [email protected]'] // no name
];

Then you do a foreach..

foreach($data as $person) {
    $contacts[] = ['name' = $person['name'], 'email' => $person['email']];
}

This will cause the error illegal string offset 'name' because the 3rd $person has no name offset.

rdelorier

Once you get your data from the Excel file you can validate it using array validation to make sure all the rows have the necessary keys.

jhansi

@SaeedPrez http://www.awesomescreenshot.com/showImage?img_id=2310077 now i am getting error like above link QueryException in Connection.php line 770: SQLSTATE[HY000]: General error:

SaeedPrez

@jhansi I can't see the screenshots, the page requires me to login..

jhansi
Snapey
Snapey
3 months ago (519,655 XP)

So what does the error show you?

Field password does not have a default value

SQL requires that you tell it a default value for the password. Either in the table configuration or by passing a password value on the insert.

Sign In or create a forum account to participate in this discussion.