How to update product image using polymorphic relaitonship - laravel

This is my update method. I'm using simple polymorphic relation morphTo() and morphOne(). I'm having trouble in updating Product model.
public function update(Request $request, Product $product)
{
$product->name = $request->name;
$product->price = $request->price;
$product->discount = $request->discount;
$product->category_id = $request->category;
$product->brand_id = $request->brand;
$product->is_active = $request->is_active;
if($request->hasFile('url')) {
$image = $request->file('url');
$filename = $image->getClientOriginalName();
$image->move(public_path('storage/products'), $filename);
$product->image->url = $request->file('url')->getClientOriginalName();
// dd($product->image->url);
}
$product->save();

Related

In Laravel, While updating Product record, it creates new record

CONTROLLER
public function updateproduct(Request $request, $id)
{
if($request->hasfile('images'))
{
foreach($request->file('images') as $file)
{
$name = time().'.'.$file->extension();
if($file->move(public_path().'/files/', $name)){
Image::create([
'images'=>$name,
'product_id'=>$product->id,
]);
}
}
}
$request->validate([
'name'=>'required',
'description'=>'required',
'images'=> 'nullable',
'price'=>'required|numeric',
'quantity'=>'required|numeric',
]);
$product = Product::findOrFail($id);
$product->name=$request->name;
$product->description=$request->description;
$product->price=$request->price;
$product->quantity=$request->quantity;
$product->update();
}
There is products table, images table and product_images table. It works fine while adding new product. But when I update the record, instead of updating data it creates new record.
$product = Product::where('id', $id)->first();
if(is_null($product)) {
$product = new Product();
}
$product->name = $request->input('name');
$product->description = $request->input('description');
$product->price = $request->input('price');
$product->quantity = $request->input('quantity');
$product->save();

For loop request Laravel

Just a quick question guys really thankful for everyone who can help.
How do I foreach loop inside create eloquent in laravel
Here is my code. I'm trying to get and match the answers for their respective survey questions
public function answer_survey(Request $request, $id)
{
$userId = Auth::user()->id;
$user = User::where('id', $userId)->first();
$userNectarPoint = UserNectarPoint::where('user_id', $userId)->first();
$survey = Survey::find($id);
$survey_questions = SurveyQuestion::where('survey_id', $survey->id)->get();
$current_nectarpt_value = $userNectarPoint->nectar_points;
$questionIds = $request->id;
$questions = $request->question;
$answers = $request->answer;
foreach ($answers as $answer) {
}
foreach ($survey_questions as $survey_question) {
$userAnsweredSurvey = new UserAnsweredSurvey;
$userAnsweredSurvey->user_id = $userId;
$userAnsweredSurvey->user_fullname = $user->first_name . ' ' . $user->middle_initial . ' ' . $user->family_name;
$userAnsweredSurvey->survey_id = $survey->id;
$userAnsweredSurvey->survey_title = $survey->title;
$userAnsweredSurvey->survey_question_id = $survey_question->id;
$userAnsweredSurvey->survey_question = $survey_question->question;
$userAnsweredSurvey->answer = $answer;
$userAnsweredSurvey->save();
}
$result_nectarpt = $current_nectarpt_value + $survey->reward_points;
$userNectarPoint->nectar_points = $result_nectarpt;
$userNectarPoint->save();
return back()->with('status', 'survey_done');
}

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 to automatic slug when i press the submit button

I want to create slug by using value of $item->name = $request->input('name'); before $item->save();
//use Illuminate\Support\Str;
private function saveItem(Request $request, $item){
$item->name = $request->input('name');
$item->slug = Str::title($item->name,"-");
$item->save();
}
When the $item->name = $request->input('name') value is Hello World,
Then after slug the output will be Hello-World
Please help.
You can generate a slug using the Str::slug() method:
private function saveItem(Request $request, $item){
$item->name = $request->input('name');
$item->slug = Str::slug($item->name);
$item->save();
}

laravel session route redirection error on multiple input fields

I have the following controller whenever i hit submit it redirects me to sales. Where as it should return admin.invoice.index page rather than sale.index. can any one please help?
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$product = new Product;
$product->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$data[]['sales'] = $sales;
$data[]['product'] = $product;
}
$data = [];
if ($request->session()->has('data')) {
$data = $request->session()->get('data');
}
Session::flash('success', 'Sale is successfully');
return view('admin.invoice.index')->with('data', $data);
}
Pass the data with with() through session.
{
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$p = new Product;
$p->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$product = Product::where('id', '=', $request['product_id'][$i])->first();
$data[$i]['sales'] = $sales;
$data[$i]['product'] = $product;
}
Session::flash('success', 'Sale is successfully');
return redirect('/invoice')->with('data', $data);
}
Then, Make a new route -
Route::get('/invoice', function(\Illuminate\Http\Request $request){
$data = [];
if ($request->session()->has('data')) {
$data = $request->session()->get('data');
}
return view('admin.invoice.index')->with('data', $data);
});
#Sohel0415
My Sales Controller is like this.
public function index()
{
$sales = Sale::orderBy('id', 'DESC')->get();
return view('admin.sales.index', compact('sales'));
}
public function create()
{
$products = Product::pluck('name', 'id', 'qty')->toArray();
return view('admin.sales.create', compact('products'));
}
public function store(Request $request)
{
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$product = new Product;
$product->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$data[]['sales'] = $sales;
$data[]['product'] = $product;
}
Session::flash('success', 'Sale is successfully');
return view('admin.invoice.index')->with('data', $data);
}
admin.invoice.index
#extends('layouts.master')
#section('content')
#foreach($data as $d)
{{$d['sales']}}
{{$d['product']}}
#endforeach
#endsection
My web.php or routes:
Route::resource('categories', 'CategoriesController');
Route::resource('products', 'ProductsController');
Route::resource('sales', 'SalesController');

Resources