我在创建产品时遇到问题,这样的错误消息出现" Model.php第2794行中的ErrorException:非法偏移类型"。
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');
});
答案 0 :(得分:1)
在您的商品模型类中,将此行protected $primaryKey = ['product_id'];
更改为protected $primaryKey = 'product_id';
这应该可以解决此错误。
答案 1 :(得分:0)
我认为因为默认名称已更改。做出这个改变并尝试。
public function category()
{
$this->belongsTo(Category::class, 'category_id', 'category_id');
}
或者图像未设置或为null,请尝试将其添加为:
if ($request->hasFile('image')) {
$data['image'] = $this->saveimage($request->file('image'));
}else{
$data['image'] = '';
}
答案 2 :(得分:0)
我明白了:
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
}
]