I want to use images of products that I register in the database - Laravel - laravel

I programmed a product registration. The registration for the database is working correctly. My problem is that I can't show the images that I registered in the database. I created an imput where the name of the image is inserted. This name is saved in the database and the image is saved with the same name, however it is saval in public. The images are inside the public / storage / products folder.
Controller:
public function index()
{
$products = Product::paginate(10);
return view('products.index', [
'products' => $products,
]);
}
public function store(Request $request)
{
// Create registration
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
// Image
if($request->file('imageProduct')->isValid()){
$nameFile = $request->imageName . '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
return redirect()->route('ProductControllerIndex');
}
}
view:
<div>
#foreach ($products as $product)
<p>
Id: {{ $product->id }}
</p>
<p>
Nome do produto: {{ $product->name }}
</p>
<p>
Preço: {{ $product->price }}
</p>
<p>
{{ $product->imageName }}
</p>
<p>
<img src="{{ asset('storage/products/'.$product->imageName) }}" alt="">
</p>
<hr>
#endforeach
</div>

The core issue here is that your Image's extension is not being saved to the database, so $product->imageName, when used in the asset() helper, doesn't generate a complete URL for the image. You'll need to refactor your code a little to get it to save:
public function store(Request $request) {
$nameFile = $request->input('imageName', '');
if($request->file('imageProduct')->isValid()){
$nameFile .= '.' . $request->file('imageProduct')->getClientOriginalExtension();
$request->file('imageProduct')->storeAs('products', $nameFile);
}
$request->merge(['imageName' => $nameFile]);
$data = $request->only('name', 'price', 'imageName');
Product::create($data);
return redirect()->route('ProductControllerIndex');
}
In the above code, the value for $nameFile is defaulted to the value in $request->input('imageName'), or an empty string '' if nothing is supplied. Next, if a valid image is uploaded, the $nameFile variable is appended with the extension. Lastly, the $request variable is updated with the name value for imageName. The remainder of the code creates the new Product with the data supplied (using the ->only() modifier) and redirect as required.
The rest of your code should be ok, as long as the file exists in the correct directory after ->storeAs() and the fully-qualified image name is saved to the database.
Note: If for whatever reason Product::create() doesn't work with this approach, you can use the new Product() ... $product->save() approach: (there might be an issue with $request->merge() using an existing key, as I can't actually test that)
$product = new Product();
$product->name = $request->input('name');
$product->price = $request->input('price');
$product->imageName = $fileName;
$product->save();

Related

Check SHA-256 Laravel

I have a system that requires a homeowner to submit a form about their guest's details. When they submit a form, each will be assigned a unique 6-digit code. This code will be hashed with SHA-256. In the admin's view, there is a list of all submitted forms. I want to do a search function where when I enter the code, the system will look through the hashed code and check if it exists or not.
This is my GuestController:
public function index()
{
//returns admin's view
$guest = Guest::all();
return view('pages.guest.index', compact('guest'));
}
public function store(Request $request)
{
$guest = new Guest;
$guest->code = random_int(100000, 999999);
$guest->hash = hash('sha256', $guest['code']);
$guest->owner_id = Auth::user()->id;
$guest->owner = Auth::user()->name;
$guest->unit = Auth::user()->unit;
$guest->guestname = $request->input('guestname');
$guest->guestphone = $request->input('guestphone');
$guest->guestic = $request->input('guestic');
$guest->guestcar = $request->input('guestcar');
$guest->numberofguests = $request->input('numberofguests');
$guest->datevisit = $request->input('datevisit');
$guest->timevisit = $request->input('timevisit');
$guest->save();
return redirect('show-pass')->with('status', 'Guest Added Successfully');
}
public function search(Request $request)
{
//Get the search value from the request
$search = $request->input('search');
//Search in the code from the list
$guest = Guest::query()
->where('code', 'LIKE', "%{$search}%")
->get();
//Return the search view with the results compacted
return view('pages.guest.search', compact('guest'));
}
This is my search result blade:
<div class="card-body">
#if($guest->isNotEmpty())
#foreach ($guest as $item)
<div class="post-list">
<p>Owner : {{ $item->owner }}</p>
<p>Unit : {{ $item->unit }}</p>
<p>Guest Name : {{ $item->guestname }}</p>
<p>Guest Phone Number : {{ $item->guestphone }}</p>
<p>Guest IC Number : {{ $item->guestic }}</p>
<p>Guest Car Number : {{ $item->guestcar }}</p>
<p>Date : {{ $item->datevisit }}</p>
<p>Time : {{ $item->timevisit }}</p>
</div>
#endforeach
#else
<div>
<h4>No guests with the code was found</h4>
</div>
#endif
</div>
Is what I'm trying to do possible? If yes, how can I edit my search method to be able to do so? May I get some help?

How Can I add a get parameter to query string of Laravel paginate?

I would like to try to append a get parameter to paginate URL in some way.
But it does not work.
enter image description here
enter image description here
I really want to add ?year=XXXX to this Query string in pagenate links
enter image description here
When any of these 1,2,3~11 buttons is clicked ,?year=XXXX will be removed.
public function list(Request $request)
{
$year = $request->year;
$companies = Company::orderBy('id', 'DESC')->paginate(15);
$data = ['companies' => $companies ,'pagenate_params' => ['year' => $year]];
return view('list', $data);
}
Blade
#foreach ($companies as $company)
<a href={{ route('next',['id' => $company->id ,'year' => $year])}} {{$year}}</a>
#endforeach
{{ $companies->appends('year' => '2022')->links() }}

Uploading files with infyom generator

I am trying to upload a file with laravel using the code generated by the infyom generator. The file seems to be uploaded but this is what is shown on the application when I view the report (C:\xampp\tmp\php7925.tmp). Provided below is the code for my application.
Thank you so much and really appreciate the help in this project.
rgds,
Form
<!-- Inf File Field -->
<div class="form-group col-sm-6">
{!! Form::label('inf_file', 'Attachments:') !!}
{!! Form::file('inf_file') !!}
</div>
Controller
{
$input = $request->all();
$infrastructure = $this->infrastructureRepository->create($input);
$file = $request->file('inf_file');
$file = $request->inf_file;
if ($request->hasFile('inf_file')){
//
if ($request->file('inf_file')->isValid()){
}
}
Flash::success('Infrastructure saved successfully.');
return redirect(route('infrastructures.index'));
}
This is how you display when you view your records,
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
<a download href="{{ asset($infrastructure->inf_file) }}">Download</a>
</div>
Managed to solve it.
public function store(CreateinfrastructureRequest $request)
{
$input = $request->all();
if ($request->hasFile('inf_file')){
//Validate the uploaded file
$Validation = $request->validate([
'inf_file' => 'required|file|mimes:pdf|max:30000'
]);
// cache the file
$file = $Validation['inf_file'];
// generate a new filename. getClientOriginalExtension() for the file extension
$filename = 'Infras-' . time() . '.' . $file->getClientOriginalExtension();
// save to storage/app/infrastructure as the new $filename
$InfrasFileName = $file->storeAs('infrastructure', $filename);
$path = "/storage/app/public/".$InfrasFileName;
}
$input['inf_file'] = $path;
$infrastructure = $this->infrastructureRepository->create($input);
Flash::success('Infrastructure saved successfully. ' . $path);
return redirect(route('infrastructures.index'));
}

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 pass id to controller in laravel 5.2

I using this method to upload the image and passing the page id so i can store the path into database but having error "Missing argument 2 for App\Http\Controllers\RoundtablesController::postImage()"
This is my form
<div class="btn-group">
{!! Form::open(array('action' => 'RoundtablesController#postImage',$tables->id, 'files'=>true)) !!}
<div class="form-group">
{!! Form::label('Profile-Picture', 'Profile Picture:') !!}
{!! Form::file('profile_image',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
</div>
This is my route
Route::post('/roundtables/settings',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
This is my controller ,the $name should get the Page Id, but look like the id not passed to here yet
public function postImage(Request $request,$name){
$table_details =Detail::find($name);
//save image
if ($request->hasFile('profile_image')) {
//add new photo
$image = $request->file('profile_image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($image)->resize(800, 400)->save($location);
$oldFilename = $table_details->profile_image;
//update database
$table_details->profile_image = $filename;
//Delete old image
Storage::delete($oldFilename);
}
$table_details->update();
Can i know where is the error? Sry i know this is very basic but i am new in laravel.
Route:
Route::post('/roundtables/settings/{id}',
['as' => 'roundtables.setting',
'middleware'=>['auth'],
'uses'=>'RoundtablesController#postImage']);
Action:
public function postImage(Request $request, $id) {
$Detail = Detail::findOrFail($id); // will return 404 or exception if record not found
if ($request->hasFile('profile_image')) {
$file = $request->file('profile_image');
$profile_image = time() . '.' . $file->getClientOriginalExtension();
$profile_image_file = public_path('images/' . $profile_image);
Image::make($image)
->resize(800, 400)
->save($profile_image_file);
$old_profile_image_file = public_path('images/'.$Detail->profile_image);
if(is_file($profile_image_file)) { // if new file successfully created
$Detail->profile_image = $profile_image; // changing profile_image
$Detail->save(); // saving
Storage::delete($old_profile_image_file);
}
}
}
in view open form like (use named route: roundtables.setting defined in router):
{!! Form::open(array('url' => route('roundtables.setting', $tables->id), 'files'=>true)) !!}
also it's a little bit strange $tables->id, are You sure that $tables is an instance of model (not an array or collection) ?
route should be like
Route::post('/roundtables/settings/{name}',['uses'=>'RoundtablesController#postImage','middleware'=>['auth']]);
Try this way...
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups#show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}

Resources