Abang Alson
Abang Alson

Reputation: 25

ErrorException in Model.php line 2794: Illegal offset type in Laravel 5.2.*

I have a problem when creating a product, an error message like this appears "ErrorException in Model.php line 2794: Illegal offset type".

enter image description here

Model Product.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name','description','image','size','price','category_id'];
    protected $primaryKey = ['product_id'];

    public function category()
    {
        $this->belongsTo(Category::class);
    }
}

Model Category.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['title'];
    protected $primaryKey = 'category_id';

    public function product()
    {
        return $this->hasMany(Product::class);
    }
}

ProductController.php

<?php

namespace App\Http\Controllers;

use App\Product;
use App\Category;
use Laracasts\Flash\Flash;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use File;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $q = $request->get('q');
        $products = Product::where('name', 'LIKE', '%'.$q.'%')->orderBy('name')->paginate(10);
        return view('admin.product.index', compact('products', 'q'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.product.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:products',
            'description' => 'required',
            'image' => 'mimes:jpeg,png|max:10240',
            'size' => 'required',
            'price' => 'required|numeric|min:1000'
        ]);

        $data = $request->only('name', 'description', 'size', 'price');
        if ($request->hasFile('image')) {
            $data['image'] = $this->saveimage($request->file('image'));
        }
        $product = Product::create($data);
        $product->categories()->sync($request->get('category_lists'));
        Flash::success('Produk ' .$product->name. ' tersimpan.');
        return redirect()->route('backend.products.index');
    }

    protected function saveimage(UploadedFile $image)
    {
        $fileName = str_random(40) . '.' . $image->guessClientExtension();
        $destinationPath = public_path() . DIRECTORY_SEPARATOR . 'images';
        $image->move($destinationPath, $fileName);
        return $fileName;
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}

create.blade.php

{!! Form::open(['route' => 'backend.products.store', 'files' => true])!!}
<div class="form-group {!! $errors->has('name') ? 'has-error' : '' !!}">
   {!! Form::label('name', 'Nama') !!}
   {!! Form::text('name', null, ['class'=>'form-control']) !!}
   {!! $errors->first('name', '
   <p class="help-block">:message</p>
   ') !!}
</div>
<div class="form-group {!! $errors->has('description') ? 'has-error' : '' !!}">
   {!! Form::label('description', 'Deskripsi') !!}
   {!! Form::textarea('description', null, ['class'=>'form-control']) !!}
   {!! $errors->first('description', '
   <p class="help-block">:message</p>
   ') !!}
</div>
<div class="form-group {!! $errors->has('price') ? 'has-error' : '' !!}">
   {!! Form::label('price', 'Harga') !!}
   {!! Form::text('price', null, ['class'=>'form-control']) !!}
   {!! $errors->first('price', '
   <p class="help-block">:message</p>
   ') !!}
</div>
<div class="form-group {!! $errors->has('size') ? 'has-error' : '' !!}">
   {!! Form::label('size', 'Ukuran') !!}
   {!! Form::number('size', null, ['class'=>'form-control']) !!}
   {!! $errors->first('size', '
   <p class="help-block">:message</p>
   ') !!}
</div>
<div class="form-group {!! $errors->has('category_lists') ? 'has-error' : '' !!}">
   {!! Form::label('category_lists', 'Kategori') !!}
   {!! Form::select('category_lists[]', [''=>'']+App\Category::lists('title','category_id')->all(), null, ['class'=>'form-control']) !!}
   {!! $errors->first('category_lists', '
   <p class="help-block">:message</p>
   ') !!}
</div>
<div class="form-group {!! $errors->has('image') ? 'has-error' : '' !!}">
   {!! Form::label('image', 'Gambar') !!}
   {!! Form::file('image') !!}
   {!! $errors->first('image', '
   <p class="help-block">:message</p>
   ') !!}
   @if (isset($model) && $model->image !== '')
   <div class="row">
      <div class="col-md-6">
         <p>Current image:</p>
         <div class="thumbnail">
            <img src="{{ url('/images/' . $model->image) }}" class="img-rounded">
         </div>
      </div>
   </div>
   @endif
</div>
{!! Form::submit(isset($model) ? 'Update' : 'Save', ['class'=>'btn btn-primary']) !!}
{!! Form::close() !!}

Routes.php

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

// Front End
Route::get('/', 'CatalogsController@index')->name('index');

// Auth
Route::auth();
Route::get('/home', 'HomeController@index');

// Back End
Route::group(['prefix' => 'backend', 'middleware' => ['auth','admin']], function() {
    Route::get('/', function() {
        return view('admin.index');
    })->name('backend.index');

    Route::resource('categories', 'CategoryController');
    Route::resource('products', 'ProductController');
});

Upvotes: 1

Views: 4198

Answers (3)

ayip
ayip

Reputation: 2543

In your Product Model class, change this line protected $primaryKey = ['product_id']; to protected $primaryKey = 'product_id'; That should resolve this error.

Upvotes: 3

Abang Alson
Abang Alson

Reputation: 25

i get this:

array:7 [▼
  "_token" => "dkbgGdfB1wP5rTRlGmKmo0rItrnV5T1pvnj65Uc3"
  "name" => "Bukan Hekel"
  "description" => "Bukan Hekel"
  "price" => "120000"
  "size" => "12"
  "category_lists" => array:1 [▼
    0 => "1"
  ]
  "image" => UploadedFile {#215 ▼
    -test: false
    -originalName: "bukanhekel.jpeg"
    -mimeType: "image/jpeg"
    -size: 54465
    -error: 0
    path: "/tmp"
    filename: "phpnjDRJA"
    basename: "phpnjDRJA"
    pathname: "/tmp/phpnjDRJA"
    extension: ""
    realPath: false
    writable: false
    readable: false
    executable: false
    file: false
    dir: false
    link: false
  }
]

Upvotes: 0

MohamedSabil83
MohamedSabil83

Reputation: 1559

I think because default name changed. make this change and try.

public function category()
{
    $this->belongsTo(Category::class, 'category_id', 'category_id');
}

or maybe image isn't set or null, try add this to be:

if ($request->hasFile('image')) {
   $data['image'] = $this->saveimage($request->file('image'));
}else{
   $data['image'] = '';
}

Upvotes: 0

Related Questions