How to pass id to controller in laravel 5.2 - laravel

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

Related

I want to use images of products that I register in the database - 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();

Download file in laravel

I am new to Laravel and I trying to capture the filename stored on the database table called "Infrastructure" so that I can create a link for users to downloading that file. The download works but I always get the wrong file stored in the directory.
So in my controller called infrastructureController.php I have these codes.
public function show($id)
{
$infrastructure = $this->infrastructureRepository->find($id);
$Attachment = $infrastructure->inf_file; // captured filename in the database
if (empty($infrastructure)) {
Flash::error('Infrastructure not found');
return redirect(route('infrastructures.index'));
}
return view('infrastructures.show')->with('infrastructure', $infrastructure);
}
In my route or web.php
I have these codes...
Route::get('/download', function(){
$name = $Attachment;
$file = storage_path()."/app/public/infrastructure/".$Attachment;
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});
and finally, in my view file, I have this
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
Download Now
</div>
Can someone point out I did wrong here...
First you are not passing the name of the attachment from your View back to your controller so change your view to:
<!-- Inf File Field -->
<div class="form-group">
{!! Form::label('inf_file', 'Attachements:') !!}
Download Now
</div>
Then in your route you need to access the name of the file like so:
Route::get('/download/{Attachment}', function($Attachment){
$name = $Attachment;
$file = Storage::disk('public')->get("infrastructure/".$Attachment);
$headers = array(
'Content-Type: application/pdf',
);
return Response::download($file, $name, $headers);
});

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

getMimeType() before moving file in Laravel

This a part of my app I'm using to put a section that admin can choose the category of the file from...
File Model
namespace App\Models;
use App\Traits\Categorizeable;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
use Categorizeable;
protected $primaryKey = 'file_id';
protected $guarded = ['file_id'];
public function packages()
{
return $this->belongsToMany(Package::class, 'package_file');
}
}
Anyway I used a trait for it...
after that it is my view:
<div class="form-group">
<label for="categorize"> categories :</label>
<select name="categorize[]" id="categorize" class="select2 form-control" multiple>
#foreach($categories as $cat)
<option value="{{$cat->category_id}}"
{{isset($file_categories) && in_array($cat->category_id,$file_categories) ? 'selected' :'' }}>
{{$cat->category_name}}</option>
#endforeach
</select>
</div>
at last this is my FilesController:
public function store(Request $request)
{
// $this->validate();....
//after validation
$new_file_name = str_random(45) . '.' . $request->file('fileItem')->getClientOriginalExtension();
$result = $request->file('fileItem')->move(public_path('files'), $new_file_name);
if ($result instanceof \Symfony\Component\HttpFoundation\File\File) {
$new_file_data['file_name'] = $new_file_name;
$new_file_data = File::create([
'file_title' => $request->input('file_title'),
'file_description' => $request->input('file_description'),
'file_type' => $request->file('fileItem')->getMimeType(),
'file_size' => $request->file('fileItem')->getClientSize(),
]);
if ($new_file_data) {
if ($request->has('categorize')) {
$new_file_data->categories()->sync($request->input('categorize'));
}
return redirect()->route('admin.files.list')->with('success', 'message');
}
}
}
Now what my problem is that as you see file() saves a .tmp file first and I need to use getMimeType() before I move it, how to modify my code?
What is the best way to do that?
App is giving me an Error
Save the mime type as a variable before you move the file and use it in the create function
$new_file_name = str_random(45) . '.' . $request->file('fileItem')->getClientOriginalExtension();
$mime_type = $request->file('fileItem')->getMimeType();
$file_size = $request->file('fileItem')->getClientSize();
$result = $request->file('fileItem')->move(public_path('files'), $new_file_name);
if ($result instanceof \Symfony\Component\HttpFoundation\File\File) {
$new_file_data['file_name'] = $new_file_name;
$new_file_data = File::create([
'file_title' => $request->input('file_title'),
'file_description' => $request->input('file_description'),
'file_type' => $mime_type,
'file_size' => $file_size,
]);

How to image update using laravel5

I don't know how to edit image using laravel5. When I update my image file It show this error:
FatalErrorException in SiteadminController.php line 1719:
Class 'App\Http\Controllers\Image' not found
Controller
public function siteadmin_update_ads(Request $request)
{
$post = $request->all();
$cid=$post['id'];
// $img=$post['ads_image'];
$v=validator::make($request->all(),
[
'ads_title'=>'required',
'ads_url' => 'required',
]
);
if($v->fails())
{
return redirect()->back()->withErrors($v->errors());
}
//$image = Image::find($cid);
else
{
$image = Image::find($cid);
if($request->hasFile('ads_image'))
{
$file = $request->file('ads_image');
$destination_path = '../assets/adsimage/';
$filename = str_random(6).'_'.$file->getClientOriginalName();
$file->move($destination_path, $filename);
$image->file = $destination_path . $filename;
$data=array(
'ads_title'=>$post['ads_title'],
'ads_url'=>$post['ads_url'],
'ads_image'=>$post['ads_image'],
);
}
// $image->caption = $request->input('caption');
// $image->description = $request->input('description');
$image->save();
}
// $i = DB::table('le_color')->where('id',$post['id'])->update($data);
$i=Ads_model::update_ads($data,$cid);
if($i>0)
{
Session::flash ('message_update', 'Record Updated Successfully');
return redirect('siteadmin_manageads');
}
else {
return Redirect('siteadmin_editads');
}
}
Model
public static function update_ads($data,$cid)
{
return DB::table('le_ads')->where('id',$cid)->update($data);
}
View
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Upload Image*</label>
<div class="col-md-9 col-sm-6 col-xs-12">
<input type='file' id="field" class='demo left' name='ads_image' data-type='image' data-max-size='2mb'/><br>
<img src="{{ url('../assets/adsimage/').'/'.$row->ads_image}}" style="height:90px;">
</div>
</div>
I don't know what is that Image, so I am at least possible help to you. But I'll try to solve it.
What you can do is:
Add backslash \ before the Image. It should look like this: \Image::find($cid);
Or else, it is a Intervention package: you need to import the Facade of Intervention Package.
add use Intervention\Image\Facades\Image;
I hope this helps you out.
you are missing the 'use' import statement for class image so its trying to find the class in the current namespace which is wrong assuming your model is stored at App namespace then add the below in the begining of controller
use App\Image

Resources