Laravel 5.1 - 错误创建产品 - 资源控制器

时间:2016-05-10 16:35:32

标签: laravel laravel-5.1 crud

我创建了一个资源控制器(CRUD)来管理产品,关于更新,删除工作的好。但是CREATE不起作用。我需要具体说明每个产品都有作者关系和类别关系。

错误:

  

SQLSTATE [23000]:完整性约束违规:1452无法添加或   更新子行:外键约束失败(2016products,   约束products_user_id_foreign外键(user_id)   参考usersid)ON DELETE CASCADE)(SQL:insert into   productsupdated_atcreated_at)值(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="{{url('admin/user')}}" class="btn btn-warning">Indietro</a>
                          <button type="submit" class="btn btn-success">Crea Prodotto</button>
                        </div>
                      </div>


                    {!! Form::close()!!}

ROUTES.PHP(关于CRUD产品)

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');

模型用户

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');    

    }

    //--//

模型产品

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());   

    }

}

模型类别

<?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');

    }



}.

移民用户

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
   public function up()

{

    Schema::create('users', function (Blueprint $table) {

        $table->increments('id');

        $table->string('name');

        $table->string('lastname');

        $table->string('username')->default('Utente');

        $table->string('birth');

        $table->string('profile')->default('image-profile/profilo.png');

        $table->string('country')->default('Paese');

        //$table->string('province')->default('Città');

        //$table->string('address');

        //$table->string('address2');

        //$table->string('phone');

        $table->string('usertype');

        $table->string('email')->unique();

        $table->string('password', 60);

        $table->boolean('social');

        $table->boolean('active')->default(0);

        $table->string('confirm_token', 100);

        $table->rememberToken();

        $table->timestamps();

    });

}






    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}

移民产品

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */

    //Up creare table
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255);
            $table->string('slug'); 
            $table->text('description');
            //mostrare una piccola descrizione del prodotto
            $table->string('extract', 300);
            $table->decimal('price', 5, 2);
            $table->string('image', 300);
            //vedere se pubblico o no
            $table->boolean('visible');
            // unsigned solo valori positivi
            //e fa riferimento al id category, 
            //Se si cancella, cancellerà tutti i prodotti con quella categoria
            //Ogni prodotto ha una categoria

            $table->integer('user_id')->unsigned();

            $table->foreign('user_id')
                  ->references('id')->on('users')
                  ->onDelete('cascade');







            $table->integer('category_id')->unsigned();

            // relazioni  
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onDelete('cascade');
            //crea // Ogni prodotto ha un autore( artista)




            // ----// 
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    //eliminare table
    public function down()
    {
        Schema::drop('products');
    }
}

移民类别

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 255)->unique();
            //Slug Nome facile per URL
            $table->string('slug');
            $table->text('description');
            //dargli un colore
            $table->string('color', 30);

            //$table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('categories');
    }
}

我注册了一个用户,因此存在用户ID 1。 谢谢您的帮助!

1 个答案:

答案 0 :(得分:0)

好的,您的名称约定似乎是正确的,现在您忘记输入user_id到您的产品,因此它不会有1-N关系。

根据Laravel's documentation,你必须使用方法save on user-&gt; product()。

$userID = Auth::user()->id; // i dont know how are you setting the authentication, but i will assume its the default.
$userObject = User::find($userID);
... do all the things with product.

$userObject->products()->save($product);