I want to insert data into order table, but the data is not inserted into the database. My code is as follows, there is no error shown. How to fix it?
$saveorder= new Order;
$saveorder->customer_id = $request->input('customer_id');
$saveorder->vendor_id = $request->input('vendor_id');
$saveorder->order_date= Carbon::now()->isoFormat('YYYY-MM-DD');
$saveorder->pickup_date=$request->input('pickup_date');
$saveorder->order_status="Pending";
$saveorder->shipping_address=$request->input('shipping_address');
$saveorder->amount=$request->input('amount');
$saveorder->payment=$request->input('payment');
$saveorder->delivery_method=$request->input('delivery_method');
$saveorder->delievery_fee=5.00;
$saveorder->order_notes=$request->input('order_notes');
$saveorder->save();
modelBelow is order model.
use HasFactory;
protected $table = 'order';
protected $guarded = ['id'];
protected $fillable = [
'order_date',
'pickup_date',
'order_status',
'shipping_address',
'amount',
'payment',
'delivery_method',
'delivery_fee',
'phone',
'order_notes',
'customer_id',
'vendor_id',
];
protected $casts = [
'id' => 'integer',
];
migration Below are my migration file.
Schema::create('order', function (Blueprint $table) {
$table->increments('id');
$table->date('order_date');
$table->date('pickup_date');
$table->string('order_status');
$table->string('shipping_address');
$table->decimal('amount', 10, 2);
$table->string('payment');
$table->string('delivery_method');
$table->string('delivery_fee');
$table->string('phone');
$table->string('order_notes');
$table->unsignedInteger('customer_id');
$table->unsignedInteger('vendor_id');
$table->timestamps();
});
No error is shown, laravel save() function does not work.
You need to debug your code a bit. Follow the steps below.
First, update your blade file by adding below code. This will display all the errors related to validation
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Second, wrap your method to save the data in try-catch block. It will show you all errors related to your code inside the function to save the data.
try {
// your code goes here
} catch (Exception $e) {
info($e->getMessage());
}
$saveorder= new Order();
$saveorder->customer_id = $request->customer_id;
$saveorder->vendor_id = $request->vendor_id;
$saveorder->order_date= Carbon::now()->isoFormat('YYYY-MM-DD');
$saveorder->pickup_date=$request->pickup_date;
$saveorder->order_status="Pending";
$saveorder->shipping_address=$request->shipping_address;
$saveorder->amount=$request->amount;
$saveorder->payment=$request->payment;
$saveorder->delivery_method=$request->delivery_method;
$saveorder->delievery_fee=5.00;
$saveorder->order_notes=$request->order_notes;
$saveorder->save();
you should use create function its good solution and clean code and give it validated input
or collect all in new var and pass it to function create
save method it's used commonly with case update object not with insert new object in database finally make dd() for the request to ensure all inputs you are inserting are come in request and ensure data type in the database compatible
This is a proper way to save data.
// validate if you need
$data = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// otherwise
$data = $request->all();
// then add extra fields
$data['order_date'] = Carbon::now()->isoFormat('YYYY-MM-DD');
$data['order_status'] = "Pending";
$data['delievery_fee'] = 500;
// and save
Order::create($data);
class Order extends Model
{
public $guarded = []; // make sure you validate the data if you use this. and remove $protected if you have.
}
Related
I have two tables named 'users' and 'requests'. In requests table, i want to update users emp_status to 'Admin' and at the same time at table 'users' too.
Here is my controller:
public function update(Request $request, $id)
{
$status = "Admin";
$admin = DB::table('users')
->where('emp_no', $id)
->update(array('emp_status'=>$status));
$forms = Requests::find($id);
$forms->emp_no = $request->get('emp_no');
$forms->emp_name = $request->get('emp_name');
$forms->email = $request->get('email');
$forms->department = $request->get('department');
$forms->emp_status = $request->get('emp_status', $admin);
$forms->justification = $request->get('justification');
$forms->save();
return redirect('admins.request')->with('Success','Employee has been changed to admin!');
}
Requests Model:
class Requests extends Model
{
protected $fillable = [
'emp_no','emp_name','email','emp_status','department','justification'
];
public function User(){
return $this->hasMany('App\Requests');
}
}
User Model:
protected $fillable = [
'emp_no', 'emp_name', 'emp_contact','gender','email','password'
];
public function Requests(){
return $this->hasOne('App\Requests');
}
When i select the 'Admin' option in the form and click approve, it should update the two tables at the same time according to emp_no. Here is the screenshot.
The Form Details blade file
How should i go about it?
Let's assume the <select> in your blade file is defined like this:
<select id="status" name="status">
<option value="Admin">Admin</option>
<option value="Normal">Normal</option>
</select>
Then in your controller you call it with this $request->status
But since your updating two tables at the same time, you should enclose the inside of the updating method with a transaction scope, so that way if any error happens during the process it would rollback:
DB::transaction(function () use ($id, $request){
$admin = DB::table('users')
->where('emp_no', $id)
->update(array('emp_status'=>$request->status));
$forms = Requests::find($id);
$forms->emp_no = $request->get('emp_no');
$forms->emp_name = $request->get('emp_name');
$forms->email = $request->get('email');
$forms->department = $request->get('department');
$forms->emp_status = $request->get('status');
$forms->justification = $request->get('justification');
$forms->save();
});
Below are the two ways to insert data in MySql through laravel
Way 1:
$post = Post::create([
'title' => $request->input('title'),
'body' => $request->input('body')
]);
Way 2:
$post = new Post;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
I just want to know which approach is better and why? Could anyone please tell which approach is better?
Model::create is a simple wrapper around this, if you look at its implementation:
public static function create(array $attributes = [])
{
$model = new static($attributes);
$model->save();
return $model;
}
save()
save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database
save() accepts a full Eloquent model instance
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);`
$post->comments()->save($comment);
create()
while in create method you are passing array, setting properties in model and persists in database in one shot.
create() accepts a plain PHP array
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
I am trying to pass $request from a function in controller to a function in model.
THis is my controller function:
PostController.php
public function store(Request $request, post $post)
{
$post->title = $request->title;
$post->description = $request->description;
$post->save();
return redirect(route('post.index'));
}
how save data in model Post.php?
I want the controller to only be in the role of sending information. Information is sent to the model. All calculations and storage are performed in the model
Thanks
You can make it even easier. Laravel has it's own helper "request()", which can be called anywhere in your code.
So, generally, you can do this:
PostController.php
public function store()
{
$post_model = new Post;
// for queries it's better to use transactions to handle errors
\DB::beginTransaction();
try {
$post_model->postStore();
\DB::commit(); // if there was no errors, your query will be executed
} catch (\Exception $e) {
\DB::rollback(); // either it won't execute any statements and rollback your database to previous state
abort(500);
}
// you don't need any if statements anymore. If you're here, it means all data has been saved successfully
return redirect(route('post.index'));
}
Post.php
public function postStore()
{
$request = request(); //save helper result to variable, so it can be reused
$this->title = $request->title;
$this->description = $request->description;
$this->save();
}
I'll show you full best practice example for update and create:
web.php
Route::post('store/post/{post?}', 'PostController#post')->name('post.store');
yourform.blade.php - can be used for update and create
<form action='{{ route('post.store', ['post' => $post->id ?? null]))'>
<!-- some inputs here -->
<!-- some inputs here -->
</form>
PostController.php
public function update(Post $post) {
// $post - if you sent null, in this variable will be 'new Post' result
// either laravel will try to find id you provided in your view, like Post::findOrFail(1). Of course, if it can't, it'll abort(404)
// then you can call your method postStore and it'll update or create for your new post.
// anyway, I'd recommend you to do next
\DB::beginTransaction();
try {
$post->fill(request()->all())->save();
\DB::commit();
} catch (\Exception $e) {
\DB::rollback();
abort(500);
}
return redirect(route('post.index'));
}
Based on description, not sure what you want exactly but assuming you want a clean controller and model . Here is one way
Model - Post
class Post {
$fillable = array(
'title', 'description'
);
}
PostController
class PostController extend Controller {
// store function normally don't get Casted Objects as `Post`
function store(\Request $request) {
$parameters = $request->all(); // get all your request data as an array
$post = \Post::create($parameters); // create method expect an array of fields mentioned in $fillable and returns a save dinstance
// OR
$post = new \Post();
$post->fill($parameters);
}
}
I hope it helps
You need to create new model simply by instantiating it:
$post = new Post; //Post is your model
then put content in record
$post->title = $request->title;
$post->description = $request->description;
and finally save it to db later:
$post->save();
To save all data in model using create method.You need to setup Mass Assignments when using create and set columns in fillable property in model.
protected $fillable = [ 'title', 'description' ];
and then call this with input
$post = Post::create([ 'parametername' => 'parametervalue' ]);
and if request has unwanted entries like token then us except on request before passing.
$post = Post::create([ $request->except(['_token']) ]);
Hope this helps.
I find to answer my question :
pass $request to my_method in model Post.php :
PostController.php:
public function store(Request $request)
{
$post_model = new Post;
$saved = $post_model->postStore($request);
//$saved = response of my_method in model
if($saved){
return redirect(route('post.index'));
}
}
and save data in the model :
Post.php
we can return instance or boolean to the controller .
I returned bool (save method response) to controller :
public function postStore($request)
{
$this->title = $request->title;
$this->description = $request->description;
$saved = $this->save();
//save method response bool
return $saved;
}
in this way, all calculations and storage are performed in the model (best way to save data in MVC)
public function store(Request $request)
{
$book = new Song();
$book->title = $request['title'];
$book->artist = $request['artist'];
$book->rating = $request['rating'];
$book->album_id = $request['album_id'];
$result= $book->save();
}
I have downloaded an open source accounting script from akaunting.com. This source code is developed in Laravel. I am trying to add one more field in the items table, but I am not able to find the insert statement in this script.
Here is the controller code. After this I am not getting any idea.
public function store(Request $request)
{
$item = Item::create($request->input());
// Upload picture
if ($request->file('picture')) {
$media = $this->getMedia($request->file('picture'), 'items');
$item->attachMedia($media, 'picture');
}
$message = trans('messages.success.added', ['type' => trans_choice('general.items', 1)]);
flash($message)->success();
return redirect()->route('items.index');
}
After a long search I got the solution.
In app/models/common/item.php we can add extra fields. The text box name and database column name should be the same.
protected $fillable = ['company_id', 'name', 'sku', 'description', 'sale_price', 'purchase_price', 'quantity', 'category_id', 'tax_id', 'enabled','expiry_date'];
I'm making my first Larevel (4) application and I want to display the date that it was created and I'm getting this problem: Unexpected data found. Unexpected data found. Unexpected data found. Data missing
when I try to do this in my blade template
#extends('layout')
#section('content')
<h3>Name: {{ $user->name }}</h3>
<p>Email: {{ $user->email }}</p>
<p>Bio: {{ $user->bio }}</p>
#endsection()
#section('sidebar')
<p><small>{{ $user->created_at }}</small></p>
#endsection()
#stop
and my controller
<?php
class UserController extends BaseController
{
public $restfull = true;
public function get_index() {
//$users = User::all();// gets them in the order of the database
$users = User::orderBy("name")->get(); // gets alphabetic by name
$v = View::make('users');
$v->users = $users;
$v->title = "list of users";
return $v;
}
public function get_view($id) {
$user = User::find($id);
$v = View::make('user');
$v->user = $user;
$v->title = "Viewing " . $user->name;
return $v;
}
}
?>
it works as soon as I take out :
<p><small>{{ $user->created_at }}</small></p>"
any ideas how to access those values, I checked and they DO exist in my table.
this is the schema of my table
CREATE TABLE "users" ("id" integer null primary key autoincrement, "email" varchar null, "name" varchar null, "bio" varchar null, "created_at" datetime null, "updated_at" datetime null);
So here's what I did to fix it.
in the migrations I did this:
class CreateTable extends Migration {
public function up()
{
Schema::create('users', function($table) {
$table->string('name');
$table->timestamps();
});
}
/* also need function down()*/
I had the insertions like this in my migrations to add some users.
class AddRows extends Migration {
/* BAD: this does NOT! update the timestamps */
public function up()
{
DB::table('users')->insert( array('name' => 'Person') );
}
/* GOOD: this auto updates the timestamps */
public function up()
{
$user = new User;
$user->name = "Jhon Doe";
$user->save();
}
}
Now when you try to use {{ $user->updated_at }} or {{ $user->created_at }} it will work! (assuming that you passed $user to the view)
There are a few things going on here that should probably be fixed. Since this is a restful controller, Laravel expects your function names to be camelCase rather than snake_case.
The way you are passing variables to the view also is not looking right. Try passing the $users variable to the view with return View::make('users')->with('users',$users);.
Another thing is you are passing a collection of users to the view, which means you won't just be able to echo user information. To get the user information out of the collection, you must iterate through the collection with a loop. (Your app will probably break again once you get more than one user in)
foreach($users as $user)
{
echo $user->name;
echo $user->email;
echo $user->bio;
}
Because the way you have your sidebar and content sections showing user information, what you probably actually want to do to get your user is something along the lines of $user = User::find(Auth::user()->id); meaning it would be returning one user and you'd be able to lose the loop.
One more thing I just seen. If you are setting up a restful controller, the proper property is public $restful = true; though I'm not sure that's actually being used anymore because you are basically setting that in routes.php with Route::controller('user', 'UserController');.