Laravel Eloquent update with custom entries - laravel

I have u CRUD project, and now I have idea to get update of one table with custom entries.
This is my controller:
public function update($id, Request $request)
{
$data = $request->only(['x', 'y', 'time']);
$device_new = Device_new::where('deviceId', $id)->first();
$device_new->x = $data['x'];
$device_new->y = $data['y'];
$device_new->datetime = $data['datetime'];
$device_new->save();
}
Is it even possible to update x, y, and datetime without edit blade, just update them with some limited values with command on some button?
Like in new controller:
public function update($id, Request $request)
{
$x='47'; $y='16';
$device_new = Device_new::where('deviceId', $id)->first();
$device_new->x = $x;
$device_new->y = $y;
$device_new->save();
}

Related

Laravel How to update value to another column in another table?

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

Call to a member function fill() on array

I am trying to update data from the product table. But, when I try to update laravel, it gives me an error which says call to a member function fill() on array. When I debug $data I got an array of key and values.
I have the following code:
public function update(Request $request,Products $product)
{
$this->products = $this->products->find($product->id);
if(!$this->products){
request()->session()->flash('error','Product not found!');
return redirect()->route('product.index');
}
$rules = $this->products->getRules('update');
$this->products = $request->validate($rules);
$data = $request->all();
$data['added_by'] = $request->user()->id;
$data['image'] = explode(',',$data['related_images'])[0];
$this->products->fill($data); //Getting error here
$status = $this->products->save();
if($status){
$request->session()->flash('success','Product updated successfully.');
} else {
$request->session()->flash('error','Sorry! there was problem updating product.');
}
return redirect()->route('product.index');
}
I want the fill() function to work so that it can update my data on the product table.
The line below is overwriting your products with an array of the keys that passed validation. You can fix it by removing the assignment (if there are errors, a 422 error will still be returned)
$this->products = $request->validate($rules);
// change to
$request->validate($rules);

why i can't call name from table food?

public function orderlist(Request $request){
$id = $request->id;
$data['order'] = Order::where('shop_id',$id)->orderBy('id')->get();
foreach($data['order'] as $orders){
$orders->shop = Shop::where('id',$orders->shop_id)->first();
$orders->food = Food::where('id',$orders->food_id)->get();
}
return $orders->food->name;
return view ('administrator.users.list_order.index',$data);
}
If you set up proper Eloquent relationships, this code could be rewritten like so:
public function orderlist(Request $request, Shop $shop){
$orders = $shop->orders()->with(['food'])->get();
return view ('administrator.users.list_order.index',compact('orders'));
}
Check out the docs here: https://laravel.com/docs/5.7/eloquent-relationships

laravel 5.7 how to pass request of controller to model and save

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

how to view order submitted by customer to the seller?

A customer can post an order to the seller. The problem is how can seller(ps) can view his order.Because each order may be submitted to different seller.
SLotController.php
public function order(Request $request)
{
$slotorder = new Slotorder;
$slotorder->name = $request->name;
$slotorder->user_name = Auth::user()->name;
$slotorder->user_id = Auth::user()->id;
$slotorder->type = $request->type;
$slotorder->quantity = $request->quantity;
$slotorder->size = $request->size;
$slotorder->ps_id = ? // i dont know how to get seller id
$slotorder->save();
return view('home');
}
User model
public function slotorder()
{
return $this->hasMany('Slotorder::class');
}
SlotOrder model
public function user()
{
return $this->belongsTo('User::class');
}
public function user()
{
return $this->belongsTo('Ps::class');
}
Ps Model
public function slotorder()
{
return $this->hasMany('Slotorder::class');
}
Update
After user click make an order, it will go to this page according to their id. For this screenshot the id for the seller is 1. So back to my question , how can i get the seller id when user submit the order. Therefore he can view the order in his dashboard.
You are using a get route, which uses the seller id, so in the method which handles this route send the variable to the view, example:
Route
Route::get('giveorder/{seller_id}',Controller#method);
Controller Method
public function method($seller_id){
return view('giveorder',compact('seller_id'));
}
Create a hidden input inside your form:
<input type="hidden" value="{{$seller_id}}" name="seller_id">
So now you can use this seller_id in your order method:
public function order(Request $request)
{
$slotorder = new Slotorder;
$slotorder->name = $request->name;
$slotorder->user_name = Auth::user()->name;
$slotorder->user_id = Auth::user()->id;
$slotorder->type = $request->type;
$slotorder->quantity = $request->quantity;
$slotorder->size = $request->size;
$slotorder->ps_id = $request->seller_id;
$slotorder->save();
return view('home');
}

Resources