How to insert data in laravel 5.2 using ajax serialize() function? - ajax

I am having a trouble implementing data insertion using laravel by passing data from my view using serialize() function to my controller.I am just starting to play around laravel but I am now stacked on this. Begging someone to help me solve this. Thanks a lot. Below are my codes.
Product Form
<form class="form-horizontal prod-form" id="prod-form" style="background-color: #e2e2e2;" method="post" enctype="multiprodt/form-data">
<fieldset>
<div class="alert alert-dismissable alert-success alert-add-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<center><h4>Data successfully saved.</h4></center>
</div>
<address></address>
<input type="hidden" name="prod_id" class="prod_id" id="prod_id" value="">
<input type="hidden" name="_token" value="<?= csrf_token(); ?>">
<div class="form-group">
<label for="inputActivity" class="col-lg-2 control-label">Product Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="prod[pharmaceutical]" id="inputPharmaceutical" placeholder="Product name" value="" style="width:260px;height:40px;" onchange="" required>
</div>
</div>
<div class="form-group">
<label for="inputActivity" class="col-lg-2 control-label">Description</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="prod[description]" id="inputDescription" placeholder="Description" value="" style="width:260px;height:40px;" onchange="" required>
</div>
</div>
<div class="form-group">
<label for="inputActivity" class="col-lg-2 control-label">Unit</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="prod[unit]" id="inputUnit" placeholder="Unit" value="" style="width:260px;height:40px;" onchange="" required>
</div>
</div>
<div class="form-group">
<label for="inputVenue" class="col-lg-2 control-label">Price</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="prod[price]" id="inputPrice" placeholder="Price" value="" style="width:260px;height:40px;" required>
</div>
</div>
<div class="form-group">
<label for="inputSponsors" class="col-lg-2 control-label">Quantity</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="prod[quantity]" id="inputQuantity" placeholder="Quantity" value="" style="width:260px;height:40px;" required>
</div>
</div>
<div class="form-group">
<label for="inputSponsors" class="col-lg-2 control-label">Amount</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="prod[amount]" id="inputAmount" placeholder="Amount" value="" style="width:260px;height:40px;" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-primary submit-prod">Submit</button>
<button class="btn btn-default">Cancel</button>
</div>
</div>
</fieldset>
</form>
Javascript Function when submit button is clicked
<script type="text/javascript">
$(".submit-prod").click(function(e){
e.preventDefault();
var button_text = $(this).text();
alert($("#prod-form").serialize());
$.post("{{ url('/addprod') }}",$("#prod-form").serialize(),function(data){
if(data.notify == "Success"){
console.log(data.notify);
}
},"json");
}); //end
</script>
Route.php
Route::group(['middleware' => 'web'], function () {
Route::post('addprod', 'Product\ProductController#store');
Route::get('/home', 'HomeController#index');
});
ProductController.php
<?php
namespace App\Http\Controllers\Product;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Product\Product as Product;
class ProductController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
public function create(){
}
public function store(Request $request){
//$product = new Product;
$prod_details = $request->all();
$query = Product::create($prod_details);
if($query){
$notification = "Success";
} else{
$notification = "Failed";
}
echo json_encode(array('notify'=>$notification));
}
}
Model: Product.php
<?php
namespace App\Product;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//
}
Sample Input:
Error Output:

Well the issue is the csrf-token please user form helper class to declare your forms or declare the token. Else you will take millenniums to solve your problem

Related

Data Not Submitting to Database

I'm making a contact page but the form data is not saving to the database. What's the solution?
ContactController.php
public function contact()
{
if($request->isMethod('post'))
{
$data = $request->all();
}
$contact = new Contact;
$contact->name = $data['contact_name'];
$contact->email = $data['contact_email'];
$contact->subject = $data['contact_subject'];
$contact->body = $data['description'];
$category->save();
return redirect()->back()->with('flash_message_success',
'Your message has been sent successfully');
}
contact.blade.php
<form action="{{ url('/contact') }}" id="main-contact-form" class="contact-form row" name="contact-form" method="post">
{{ csrf_field() }}
<div class="form-group col-md-6">
<input type="text" name="contact_name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group col-md-6">
<input type="email" name="contact_email" class="form-control" required="required" placeholder="Email">
</div>
<div class="form-group col-md-12">
<input type="text" name="contact_subject" class="form-control" required="required" placeholder="Subject">
</div>
<div class="form-group col-md-12">
<textarea name="description" id="message" required="required" class="form-control" rows="8" placeholder="Your Message Here"></textarea>
</div>
<div class="form-group col-md-12">
<input type="submit" name="submit" class="btn btn-primary pull-right" value="Submit">
</div>
</form>
Routes:
Route::get('contact', function(){
return view('contact');
});
Route::post('contact', function(){
return view('contact');
});
Use $contact->save(); not $category->save(); and also remove the if statement (for now): if($request->isMethod('post')) {
Your route should be:
Route::post('contact', 'ContactController#contact')->name('contact');

Laravel : no errors and no update on database happens after saving the edit

I have two tables, user and technicien, with a one to one relation. After editing technicien information through edit form and saving, no update happens on database and no errors as well.
Here is my code:
controllers
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['technicien'=>$technicien])->with('user',$user);
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
$user->nom = $request->update('nom');
return redirect('/technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien->technicien ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')-
>name('technicien.update');
You just need to pass parameters to update function.
Read docs
public function update(Request $request, $id)
{
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update([
'nom' => $request->nom,
'premon' => $request->premon,
'email' => $request->email
]);
return redirect('/technicien');
}
Also from the docs
You should define which model attributes you want
to make mass assignable. You may do this using the $fillable property
on the model.

Update on "user" and "technicien" with one to one connection

I have two tables user and technician with one to one connection, technician inherits from user. After editing technician information through edit form and saving no update happens on tables user and technician. and no errors as well.
Here is my code:
Controllers
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['technicien'=>$technicien])->with('user',$user);
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
$user->nom = $request->update('nom');
return redirect('/technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien->technicien ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form- control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
Route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')->name('technicien.update');
Model1
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class technicien extends Model
{
protected $fillable = [
'moyenne_avis', 'actif',
];
use SoftDeletes;
protected $guarded = [];
protected $dates = ['deleted_at'];
public function zoneintervention()
{
return $this->belongsToMany('App\zoneintervention','technicien_zone','technicien_id','zoneintervention_id');
}
public function metier()
{
return $this->belongsToMany('App\metier','technicien_metier','technicien_id','metier_id');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function tarificationtache()
{
return $this->belongsToMany('App\tarificationtache','technicien_tarificationtache','technicien_id','tarificationtache_id');
}
}
Model2
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function technicien()
{
return $this->hasOne('App\technicien');
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password','nom','prenom','tel','mobil','role',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
controler
public function edit($id)
{
// better to use findOrFail (it will throw an exception about missing
objects)
$technicien = technicien::findOrFail($id);
return view('technicien.edit', compact('technicien'));
}
public function update(Request $request, $id)
{
$technicien=technicien::findOrFail($id);
$technicien->user->update($request->get('user'));
$technicien->update($request->get('technicien'));
return redirect('/technicien');
}
and the view
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien ) }}"
method="post">
{{csrf_field()}}
{{ method_field('patch') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control"
name="user[nom]" value="{{$technicien->user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[prenom]" value="{{$technicien->user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[tel]" value="{{$technicien->user->tel}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[mobil]" value="{{$technicien->user->mobil}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[role]" value="{{$technicien->user->role}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control"
name="user[email]" value="{{$technicien->user->email}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control"
name="user[password]" value="{{$technicien->user->password}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="technicien[moyenne_avis]"
class="form-control" value="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="technicien[actif]"
class="form-control" value="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-
control btn btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Try to do with One to One relation.
Make relation for user table and technician table, then try to do update.
Try this in controller
$user = User::with('technicien')->find($id);
$data['id'] = $id;
$data = $this->validate($request, [
'moyenne_avis' => 'required',
]);
$user->technicien()->whereUserId($data['id'])->update(['moyenne_avis' => $data['moyenne_avis']
]);
return redirect('/technicien')->with('Success', 'Records updated');
Also change form method as below in ur view.blade
<form action="{{ action('TechnicienController#update', $user->id) }}" method="post">
also, instead of {{ method_field('PATCH') }} use this <input name="_method" type="hidden" value="PATCH">
Note: Table name should be plural for controller and model name.
eg: Table name: users
Controller name: UserController
Model name: User
Make sure this same in urs too.

Laravel Sending from data to database

I am using laravel 5.2 and i am curently developing a messaging system for my app. i am trying to send messages to the database, but i keep getting this error "Call to undefined method Illuminate\Database\Query\Builder::messages()"
My MessageController is as Follows:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use App\Http\Requests;
use App\Message;
class MessageController extends Controller
{
public function CreateMessage(Request $request)
{
$meso = new Message();
$meso->body = $request['body'];
$meso->subject = $request['subject'];
$request->user()->messages()->save($meso) ;
return redirect()->route('mail');
}
}
Here is my routes file
Route::post('send', 'MessageController#CreateMessage');
and here is my form:
<form role="form" class="form-horizontal" method="POST" action="{{ url('/send') }}">
<div class="form-group">
<label class="col-lg-2 control-label">To</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="inputEmail1" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Cc / Bcc</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="cc" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Subject</label>
<div class="col-lg-10">
<input type="text" placeholder="" id="inputPassword1" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea rows="10" cols="30" class="form-control" id="" name=""></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<span class="btn green fileinput-button">
<i class="fa fa-plus fa fa-white"></i>
<span>Attachment</span>
<input type="file" name="files[]" multiple="">
</span>
<button class="btn btn-send" type="submit">Send</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</div>
</div>
</form>
Someone help me debug this error
You should create messages() relationship in User model:
public function messages()
{
return $this->hasMany('App\Message');
}
Also, you need to have user_id foreign key defined in messages table to make the relationship work.
Try this:
$request->user()->messages->save($meso);
instead of:
$request->user()->messages()->save($meso);

Laravel 5.2 cannot update record

I cannot seem to update my record.
My controller
public function add()
{
return view('cars.add');
}
public function edit($id)
{
$car = Cars::whereId($id)->firstOrFail();
return view('cars.edit', compact('car'));
}
public function store(CarFormRequest $request)
{
$car = new Cars(array(
'name' => $request->get('name'),
'color_id' => $request->get('color')
));
$car->save();
$car->position_id = $car->id;
$car->save();
session()->flash('status', 'Successfully Added a Car!');
return view('cars.add');
}
public function update($id, CarFormRequest $request)
{
$car = car::whereId($id)->firstOrFail();
$car->name = $request->get('name');
$car->color_id = $request->get('color');
if($request->get('status') != null) {
$car->status = 0;
} else {
$car->status = 1;
}
$car->save();
return redirect(action('CarController#edit', $car->id))->with('status', 'The ticket '.$id.' has been updated!');
}
my routes:
Route::get('/', 'PagesController#home');
Route::get('/about', 'PagesController#about');
Route::get('/contact', 'PagesController#contact');
Route::get('/cars', 'CarsController#index');
Route::get('/cars/edit/{id?}', 'CarsController#edit');
Route::post('/cars/edit/{id?}', 'CarsController#update');
Route::get('/cars/add', 'CarsController#add');
Route::post('/cars/add', 'CarsController#store');
here is my view:
<div class="container col-md-8 col-md-offset-2">
<div class="well well bs-component">
<form class="form-horizontal" method="post">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<input type="text" id="color_id" name="color_id" value="{!! $car->color_id !!}">
<fieldset>
<legend>Edit Car Information</legend>
<div class="form-group">
<label for="title" class="col-lg-2 control-label">Car Name</label>
<div class="col-lg-10">
<input type="text" value="{{ $car->name }}" class="form-control" id="name" placeholder="Car Name">
</div>
</div>
<div class="form-group">
<label for="title" class="col-lg-2 control-label">Car Color</label>
<div class="col-lg-10">
<div class="btn-group" data-toggle="buttons">
<label id="opt1" class="btn btn-primary">
<input type="radio" name="color" id="option1" autocomplete="off"> Red
</label>
<label id="opt2" class="btn btn-primary">
<input type="radio" name="color" id="option2" autocomplete="off"> Blue
</label>
<label id="opt3" class="btn btn-primary">
<input type="radio" name="color" id="option3" autocomplete="off"> Yellow
</label>
<label id="opt4" class="btn btn-primary">
<input type="radio" name="color" id="option4" autocomplete="off"> Green
</label>
<label id="opt5" class="btn btn-primary">
<input type="radio" name="color" id="option5" autocomplete="off"> Black
</label>
<label id="opt6" class="btn btn-primary">
<input type="radio" name="color" id="option6" autocomplete="off"> White
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
</div>
The $id variable in whereIn must be array and you need to specify the database column too. This should be like -
public function edit($id)
{
$car = Cars::whereId('id', [$id])->firstOrFail();
return view('cars.edit', compact('car'));
}
Change all occurrence of
$car = car::whereId($id)->firstOrFail();

Resources