How to automatic slug when i press the submit button - laravel-5

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

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

How to update product image using polymorphic relaitonship

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

How to select specfic id and update in Laravel?

I'm studing Laravel CRUD.
Laravel Framework is 6.18.15
I would like to select of a record and update.
This is photo gallery.
Now if I click one of photo I can get below URL
https://mywebsite.net/public/edit?id=59
but in edit.blade.php I got this error
Undefined variable: id
Could someone teach me correct code please?
These are current code
Controller UPDATED
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
public function editpcs(Request $request)
{
$this->validate($request, [
'title' => 'required',
'image' => 'required|mimes:jpeg,jpg'
]);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = time().'.'.$request->image->getClientOriginalExtension();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(1280, null, function ($image) {$image->aspectRatio();});
$image_resize->save(public_path('images/ServiceImages/' .$filename));
}
$request->image->move(public_path('images'), $input['image']);
$input['title'] = $request->title;
// ImageGallery::update($input);
$update = DB::table('image_gallery')->where('id', $id)->update( [ 'title' => $request->title, 'image' => $request->image]);
return view('edit',compact('images'))->with('sucess','sucessfully updated');
}
web.php
//edit view
Route::get('edit', 'ImageGalleryController#edit');
Route::post('edit', 'ImageGalleryController#edit');
//edit procces
Route::get('editpcs', 'ImageGalleryController#editpcs');
Route::post('editpcs', 'ImageGalleryController#editpcs');
UPDATE
#if($images->count())
#foreach($images as $image)
<div class='text-center'>
<small class='text-muted'>{{$image['id']}}/ {{$image['title']}} </small>
</div>
#endforeach
#endif
MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
class ImageGallery extends Model
{
protected $table = 'image_gallery';
protected $fillable = ['title', 'image'];
}
Actually $id is really undefined here, it would be $request->route('id') or request('id') or $_GET['id'] or $request->input('id') :
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::findOrFail($id); // use findOrFail() id not exist in table, it throw a 404 error
return view('edit',compact('images'));
}
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$id = $_GET['id'];
$country = $_GET['country'];
In laravel you can to use Input::get(), But Input::get is deprecated in newer version of laravel, prefer the $request->input instead of Input::get :
$id= $request->input('id');
$country= $request->input('country');
It looks to me like this function:
public function edit(Request $request)
{
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
Should be something like this perhaps?
public function edit(Request $request)
{
$id = $request->input('id', null);
$images = ImageGallery::find($id);
return view('edit',compact('images'));
}
As it is, $id appears to be undefined before you attempt to pass it into the find() method. But according to your URL it is in the $request object. So you need to get it from there and into the function. You can read about this method in the docs.
public function edit(Request $request)
{
$id = request('id');
$images = ImageGallery::where('id',$id)->first();
return view('edit',compact('images'));
}

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

Passing variables,arrays and objects to view with compact

I have a method in laravel that aims to pass data to views. I have data in variables, arrays and objects.
This is the method
public function view($id){
$id = request()->segment(2);
$items = Role::all(['name', 'display_name']);
return view('text.ServicesEditUser',compact('items',$items));
}
I also have this code
$uid = Auth::id();
$settings = Settings::where('user_id','=',Auth::id())->first();
return view('text.settings',compact('settings'));
that i want to incorporate to the code above. Once i pass the settings to the view, i can access data like $settings->language for instance. I also want to pass a variable which is
$title = 'degrees of tilt';
to the first code snippet's compact method.
This is the method now with all the data i want to pass to the view
public function view($id){
$id = request()->segment(2);
$title = 'Tilt in degrees';
$settings = Settings::where('user_id','=',Auth::id())->first();
$users = User::where('id','=',$id)->get();
$items = Role::all(['name', 'display_name']);
return view('text.ServicesEditUser',compact('items',$items));
}
How do i pass $settings ,$title,$users , $items to the view and how do i access each in view?
When returning a view you can pass multiple variables like this.
return view('text.ServicesEditUser')
->with(compact('items',$items))
->with('variable2', $variable2);
See here the documentation about this - Laravel Views.
In controller:
$variable = "Var";
$array = ["first" => "a", "second" => "b"];
$object = (object) $array;
return view('view',compact(['variable', 'array', 'object']));
In view:
{{$variable}}
{{$array['first']}}
{{$object->first}}
compact() doesn't need dollar at start.
You can just add your code to view by:
$title = 'My title';
$settings = ['my', 'settings',];
return view('text.settings', compact('title', 'settings'));
Anyway you can pass your variables by array:
$settings = ['my', 'settings',];
return view('text.settings', [
'title' => 'Title',
'settings' => $settings,
]);
The last option is with() method:
return view('text.settings')
->with('settings', $settings)
->with('title', 'My title');
Get access to variables in the view by {{ $title }} and
#foreach ($settings as $sett)
{{ $sett }}
#endforeach
This did also work
public function view($id){
$id = request()->segment(2);
$title = 'Degrees of tilt';
$settings = Settings::where('user_id','=',Auth::id())->first();
$users = User::where('id','=',$id)->get();
$items = Role::all(['name', 'display_name']);
return view('text.ServicesEditUser', compact('title', 'settings','users','items'));
}
in the blade view
<p>{{$title}}</p>
{{$settings->language}}
#foreach($items as $item)
<option value="{{$item->name}}">{{$item->display_name}}</option>
#endforeach
#foreach($users as $user)
<option value="{{$user->id}}">{{$user->email}}</option>
#endforeach
In settings
#if($settings)
$settings->language
#endif

Resources