dimanche 29 novembre 2015

Laravel insert FOREIGN KEY in Form Request method

in my application some tables are relationShip and i must be insert FOREIGN KEY to table as User id. i dont have any problem with create new instanse from model and use save() method. but i like to use Form Request method to create and update records,

i get this error and i can not solve that:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a >child row: a foreign key constraint fails (epaypro.merchand_web_service, >CONSTRAINT merchand_web_service_user_id_foreign FOREIGN KEY (user_id) >REFERENCES users (id)) (SQL: insert into merchand_web_service >(updated_at, created_at) values (2015-11-29 11:31:54, 2015-11-29 11:31:54))

this is my model:

namespace app;
use Illuminate\Database\Eloquent\Model;
use Morilog\Jalali\jDate;

class Merchant extends Model
{
    protected $table = 'merchand_web_service';
    protected $fillable = ['customer_key', 'company_name', 'company_logo'];

    /**
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

store method on Controller:

public function store(StoreMerchantWebServiceRequest $request)
{
    Merchant::create($request->all());
    return redirect()->route('post.index');
}

StoreMerchantWebServiceRequest class:

class StoreMerchantWebServiceRequest extends Request
{
    public function authorize()
    {
        if (Auth::check()) {
            return true;
        } else
            return false;
    }

    public function forbiddenResponse()
    {
        return Response::make(trans('message.permission_denied'), 403);
    }

    public function rules()
    {
        return [
            'agent_company_name' => 'required',
            'agent_company_logo' => 'mimes:jpg,jpeg,bmp,png|max:300',
        ];
    }
}

My Test (in controller):

public function store(StoreMerchantWebServiceRequest $request)
{
    $order = Merchant::create($request->all());
    $this->user_id = Auth::user()->id;
    $order->save();
    return redirect()->route('post.index');
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire