i created a resource controller (CRUD) to manage products, about update,delete work good. But CREATE doesnt work. i need specific that each product have a author relation and category relation.
THE ERROR:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
2016
.products
, CONSTRAINTproducts_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
) ON DELETE CASCADE) (SQL: insert intoproducts
(updated_at
,created_at
) values (2016-05-10 18:34:38, 2016-05-10 18:34:38))
PRODUCTCONTROLLER.PHP
namespace dixard\Http\Controllers\Admin;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Product;
use dixard\Category;
use dixard\User;
// ci serve per validare
use Validator;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::orderBy('id', 'desc')->paginate(20);
return view('admin.product.index', compact('products'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//prendo informazioni sulla categorie, mi prendo is e name.
// quando l'Admin crea un prodotto POTRA scegliere la categoria
$categories = Category::orderBy('id', 'desc')->lists('name', 'id');
$users = User::orderBy('id', 'desc')->lists('username', 'id');
return view('admin.product.create', compact('categories', 'users'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = [
'name' => 'required',
'description' => 'required',
'price' => 'required',
'image' => 'required',
];
$messages = [
'name.required' => 'Campo titolo prodotto richiesto',
'description.required' => 'Campo descrizione richiesto',
'price.required' => 'Campo prezzo richiesto',
'image.required' => 'Campo Url immagine richiesto'
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect('admin/product/create')->withErrors($validator);
}else {
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = [
'name' => $request->get('name'),
'slug' => $request->get('name'),
'description' => $request->get('description'),
'extract' => $request->get('description'),
'price' => $request->get('price'),
'image' => $request->get('image'),
'visibile' => $visible,
];
$product = Product::create($data);
return redirect('admin/product')->with('message', 'Prodotto creato con successo!');
//return $data;
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show(Product $product)
{
return $product;
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit(Product $product, User $user)
{
$categories = Category::orderBy('id', 'desc')->lists('name', 'id');
$users = User::orderBy('id', 'desc')->lists('username', 'id');
return view('admin.product.edit', compact('categories', 'users','product'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Product $product)
{
$id= $request->get('id');
// i want ignora id of user edited
$rules = [
'name' => 'required|unique:products'.',name,' . $id,
'description' => 'required',
'price' => 'required',
'image' => 'required',
];
$messages = [
'name.required' => 'Campo titolo prodotto richiesto',
'name.unique' => 'Campo titolo già esistente',
'description.required' => 'Campo descrizione richiesto',
'price.required' => 'Campo prezzo richiesto',
'image.required' => 'Campo Url immagine richiesto'
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect()->route('admin.product.edit', $request->get('id'))->withErrors($validator)->withInput();
}
// if there is not any error go to update
else{
// if email id different by input, so if email input update also email
if( $product->name != $request->get('name') ){
$s = new Product;
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = array(
'name' => $request->get('name'),
'slug' => $request->get('name'),
'description' => $request->get('description'),
'extract' => $request->get('description'),
'price' => $request->get('price'),
'image' => $request->get('image'),
'name' => $request->get('name'),
'user_id' => $request->get('user_id'),
'category_id' => $request->get('category_id'),
'visible' => $visible,
);
$s->where('id', '=', $request->get('id'))->update($data);
return redirect('admin/product')->with('message', 'Utente aggiornato con successo!');
}
// If email input doesnt change update all ( not email)
else{
$s = new Product;
$visible = (isset($_POST['visible']) == '1' ? '1' : '0');
$data = array(
'slug' => $request->get('name'),
'description' => $request->get('description'),
'extract' => $request->get('description'),
'price' => $request->get('price'),
'image' => $request->get('image'),
'name' => $request->get('name'),
'user_id' => $request->get('user_id'),
'category_id' => $request->get('category_id'),
'visible' => $visible,
);
$s->where('id', '=', $request->get('id'))->update($data);
return redirect('admin/product')->with('message', 'Utente aggiornato con successo!');
}
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy(Product $product)
{
$deleted=$product->delete();
if(isset($deleted))
{
return redirect('admin/product')->with('message', 'Prodotto eliminato con successo!');
} else {
return redirect('admin/product')->with('message-error', 'Prodotto non eliminato');
}
}
}
CREATE.PHP
{!! Form::open(['route'=>'admin.product.store', 'class'=>'form-horizontal form-label-left']
)!!}
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Titolo Prodotto<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="name" name="name" class="form-control col-md-7 col-xs-12" placeholder="titolo prodotto">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="lastname">Descrizione<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="textarea" id="description" name="description" class="form-control col-md-7 col-xs-12">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Prezzo €<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="price" name="price" class="form-control col-md-7 col-xs-12" placeholder="prezzo">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Immagine<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="image" name="image" class="form-control col-md-7 col-xs-12" placeholder="Url immagine">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Categoria<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{!! Form::select('category_id', $categories, null, ['class'=>'form-control col-md-7 col-xs-12'])!!}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="username">Autore<span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
{!! Form::select('user_id', $users, null, ['class'=>'form-control col-md-7 col-xs-12'])!!}
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="active">Attivo
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="checkbox" name="visible" id="checkbox-create" class="form-control col-md-7 col-xs-12 js-switch" value="1" checked>
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<a href="" class="btn btn-warning">Indietro</a>
<button type="submit" class="btn btn-success">Crea Prodotto</button>
</div>
</div>
{!! Form::close()!!}
ROUTES.PHP (about CRUD products)
Route::bind('product', function($id) {
return dixard\Product::where('id', $id)->first();
});
Route::get('admin', function(){
return view('admin.index')
;
});
Route::resource('admin/category','Admin\CategoryController');
Route::bind('category', function($category){
return dixard\Category::find($category);
});
////////////////// ADMIN Users ///////////////////////////////////////////////
Route::resource('admin/user','Admin\UserController');
Route::bind('user', function($user){
return dixard\User::find($user);
});
////////////////// ADMIN PRODUCT ////////////////////////////////////////////////
Route::resource('admin/product','Admin\ProductController');
MODEL USER
namespace dixard;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use dixard\Product;
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'username',
'lastname',
'birth',
'profile',
'country',
//'province',
//'address',
//'address2',
//'phone',
'usertype',
'email',
'password',
'social',
'confirm_token',
'active',
];
// Ogni utente HA tanti prodotti.
public function products()
{
return $this->hasMany('dixard\Product');
}
//--//
MODEL PRODUCT
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\User;
use dixard\Category;
class Product extends Model
{
protected $table = 'products';
protected $fillabile = ['name','slug','description','extract','image','visible','price',
'category_id','user_id'];
public function user() {
return $this->belongsTo('dixard\User');
}
public function category() {
return $this->belongsTo('dixard\Category');
}
//----//
public function __construct()
{
if(!\Session::has('cart')) \Session::put('cart',array());
}
}
MODEL CATEGORY
<?php
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\Product;
class Category extends Model
{
protected $table = 'categories';
// gli dico che voglio scrivere questo campi
protected $fillable = [
'name',
'slug',
'description',
'color',
];
public $timestamps = false;
public function products() {
return $this->hasMany('dixard\Product');
}
}.
Thank you for your help!
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire