How to use session with id? - laravel-5.8

I have an order and I want to after save, get in session current id of order for next page reports.
use Session;
public function store(Request $request)
{
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->title = $request->title;
$order->body = $request->body;
$order->id = $request->session()->get('id');
$order->description = $request->description;
$order->save();
session(['order_id' => $order_id]);
return redirect()->route('reports.index')->with('order_id', $request->id);
}
In notes page has a input hidden for get session of article id.
<input type="hidden" class="form-control" value="{{ Session::get('order_id') }}" name="id" id="id">
But I see input hidden. It is blank . "".

I'm confused here
session(['order_id' => $order_id]);
return redirect()->route('reports.index')->with('order_id', $request->id);
when you're returning something with "->with()" it stores in session so why use session() ? and $order_id is not defined in your method.
and best way to put something in session is like this
Session::put('order_id');
I think if you do this
->with('order_id', $order->id); // You will get the current order id created

Related

How to update a product in Laravel 5.8

I have a product that I want to edit. Please see the following code.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $request->file('image')->getClientOriginalName();
}
$product->update();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
product.blade.php
<form class="form-horizontal" action="{{ route('products.update', $product->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
.
.
.
Everything changes except the image. I tried it, but, I did not succeed. What's the solution? I want to update the image in the database.
OK, I go to database now, I changed in image to picture, then I go my project, and I tested this again.
But it did not event for me.
I changed
public function update(ProductRequest $request, Product $product)
To
public function update(Request $request, Product $product)
To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. See the updates section in the documentation.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $request->file('image')->getClientOriginalName();
}
$product->save();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
Update 1
Assuming you have debugged the above and $request->file('image')->getClientOriginalName() is returning the expected value, it's possible that you are using field whitelisting on your model and haven't added the image field to the whitelist. Make sure that image is in the $fillable array on your model.
class Product extends Model
{
protected $fillable = [
'user_id',
'title',
'body',
'price',
...
'image'
];
Update 2
If $request->file('image') is returning null then that would suggest your form is not submitting the files. Ensure your <form> element has the enctype="multipart/form-data" attribute included in the tag.
Update 3
If your already including the required enctype="multipart/form-data" tags in the <form> element then I would suggest doing the following.
Place dd($request->all()); at the top of your update(ProductRequest $request, Product $product) method. Post the form and check the output.
If the file is not included in the output, change from using ProductRequest $request to the default Request $request (Illuminate\Http\Request) and try it again. There could be something in your ProductRequest class that is causing a problem.
As a small critique, you could improve your code in the following ways.
・Use hasFile() instead of has().
・Use $product-image = $filename instead of $product->image = $request->file('image')->getClientOriginalName();.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $filename;
}
$product->save();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
make sure your has
enctype="multipart/form-data"
property

How can I pass username in controller?

Username is store in my session. I am working on leave management module.
My Leave module's table has these fields
User Name, Leave Type, Duration, Status, & Action.
Apart from username all details I can insert and list in list view.
But my user name is store in session.
How can i get it from session and store in database In Username field??
Code in my view file
#if(Session::has('key'))
<?php $username = Session::get('key')['username']; ?>
#endif
<input type="hidden" name="username" value="<?php echo $username ?>">
Code In My controller file
public function leaveApplication(Request $request)
{
$leave = new LeaveManagement();
$leave->username = $request->get('username');
$leave->leaveType = $request->get('leaveType');
$leave->startDate = $request->get('startDate');
$leave->endDate = $request->get('endDate');
$leave->fromLeave = $request->get('fromLeave');
$leave->fromHalfDayLeaveType = $request->get('fromHalfDayLeaveType');
$leave->toLeave = $request->get('toLeave');
$leave->toHalfDayLeaveType = $request->get('toHalfDayLeaveType');
$leave->fullDayLeave = $request->get('fullDayLeave');
$leave->typeOfLeave = $request->get('typeOfLeave');
$leave->reasonForLeave =$request->get('reasonForLeave');
$leave->status = 'Pending';
$leave->save();
return redirect('leave');
}
You can use Laravel global session helper: session(keyName).
To get username from session and store it in database:
$username = session('username');
$leave = new Leave();
$leave->username = $username;
$leave->save();
For more information on Laravel session see Laravel Session
you can get object from your session and access to its attributes.some thing like:
$user = session()->get('user')
$username = $user->username
or after logging you can access your user's username with:
auth()->user()->username
After login, Auth maintains user table fields in it. You can access it like that -
echo Auth::user()->name or echo Auth::user()->email
It will return the expected values as : "usersname" and "useremail#domain.com".
If you are not using Auth, then you can get username from your session and save it in DB like that -
$user = session()->get('user')
$username = $user->username;
$leave = new LeaveManagement();
$leave->username = $username;
$leave->save();
Hope this will help you.

Laravel - Calculate minimum value from multiple fields in controller

I want to calculate the minimum value from a collection of form fields.
I have one-to-many relationship, where one shop can have many items ans that is working fine without any errors.
My form
<form action="{{ route('form_submit') }}" method="post">
#csrf
<h3>Item 1</h3>
<input type="text" name="item[]">
<input type="text" name="price[]">
//Like this I can add many fields
<input type="submit">
</form>
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//I tried
$price_group = collect($item->price)->where('shop_id', $shop->id);
$min_price = min($price_group);
$item->save();
}
Route
Route::post('/{id}', 'Controller#store')->name('form_submit');
But it does not calculate the minimum price. When I dd($min_price), its total blank. What am I missing here?
I think is just...
$items = Item::where('shop_id', $shop->id)->get();
$min = $items->min('price');
And take a look on eager loading for relations. It's much better.
I solved this by #Jonas's solution. And I make this my answer.
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//This works
$min_price = min(request('price'));
$item->save();
}

Missing argument In my controller

Hey I am trying to update user profile by sending an id to controller. Every time I submit my form it gives me error missing argument. I have defined route and included id parameter in my controller function but then tooo I get the error.
Code for my controller is
public function update_avatar(Request $request,$id)
{
$this->validateInput($request);
$u = User::findOrFail($id);
dd($u);
//Handle the user upload of avatar
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save(public_path('/uploads/'.$filename));
}
$user = Auth::user();
$user->name = $request->name;
dd($user->name);
$user->email = $request->email;
if($request->password == null)
{
$user->password = $u->password;
}
$user->password = $request->password;
$user->avatar = $filename;
$user->role = 'admin';
$user->save();
return view('/adminPanel/adminProfile',array('user' => Auth::user()));
}
code of my view
<form class="form-horizontal" role="form" enctype="multipart/form-data" action="{{ route('profile', ['id' => $user->id]) }}" method="post">
And my route is
Route::post('/adminPanel/id/adminProfile',
'AdminProfileController#update_avatar')
->name('profile')->middleware('admin');;
In your route use. You missing parenthesis. When you pass id or any value using route, you have must use parenthesis for this.
Route::post('/adminPanel/{id}/adminProfile','AdminProfileController#update_avatar')->name('profile')->middleware('admin');

How to store multiple images paths into database in laravel?

I am working on multiple image upload in laravel. Uploading is successful but, i got an issue. For later use i should store in database. For single column it easy but for different column for different images i couldnot do it.
Here is my image upload code
$images = [];
$destDir = "public/uploads/";
if($request->file('image1')) $images[]=$request->file('image1');
if($request->file('image2')) $images[]=$request->file('image2');
if($request->file('image3')) $images[]=$request->file('image3');
foreach($images as $image)
{
if(!empty($image))
{
$imageName = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension();
$temPath = $image->getRealPath();
$enImg = mt_rand(1111,9999).".".$extension;
$newPath = $destDir.$enImg.".".$extension;
move_uploaded_file($temPath, $newPath);
}
}
I have a feeling you are approaching this in a way that is making it more difficult for you. Instead of creating multiple separate file inputs in your form you can only set a multiple file input and set the name of the input to an array like so:
<form action="demo_form.asp">
Images: <input type="file" name="images[]" multiple>
<input type="submit">
</form>
Then in your php you can do something like this:
if (isset($request->all()['images'])) {
$this->persistUserImages($request->all()['images'], $userId);
}
/**
* Persists user images to storage and DB
*
* #param array $userImages
* #param int $userId
* #return array
*/
private function persistUserImages(array $userImages, $userId = 1)
{
if (empty($userImages)) {
return [];
}
$uploadedUserImagesFilenames = $this->uploadUserImagesToCloud($userImages, $userId);
foreach ($uploadedUserImagesFilenames as $filename) {
$userImage = new UserImage([
'user_id' => $userId,
'filename' => $filename,
'visible' => 1
]);
$userImage->save();
}
}
You can do like this this. In your blade,
<form action="{{url('path')}}" methos="post" enctype="multipart/form-data">
Images: <input type="file" name="images[]" multiple>
<input type="submit">
</form>
In you method,
public function store(Request $request){
foreach ( $request->images as $image) {
Model::create([
'image_url' => $image,
]);
}
}
Or
follow below link. It's very easy way to solve this problem.
Multiple Image Upload In Laravel
Hope you can solved your problem.
create a pivot table and store images in separate rows..
Table schema:- `images` table
columns `id`,`user_id`(foreign key),`image_path`
store your $newPath in this table every time..

Resources