I Cannot able to pass the id in route file in laravel - laravel

I am declaring the above thing in the route for edit of my data.
Route::get('editproduct/{id}', 'HomeController#Edit_Product');
Above is my editproduct.blade.php page
<?php
$id = $_GET['eid'];
$product_info = DB::select("SELECT * FROM `product` WHERE `pid` = '".$id."'");
foreach($product_info as $detail)
{
$actual_image = 'theme/uploads/'.$detail->pimage;
$product_image = $detail->pimage;
$product_name = $detail->pname;
$product_price = $detail->pprice;
}
?>
#include('include/header')
<div class="tab-pane add-product-view" id="profile">
<form name="add_product" method="post" enctype="multipart/form-data" role="form" action="{{ url('edit-product-process') }}">
{{ csrf_field() }}
<div class="form-label">Add Image: </div>
<div class="form-field"><input type="file" name="add_image" id="add_image" value="{{asset($actual_image)}}" /></div>
<img src="{{asset($actual_image)}}" width="50" height="50" />
<div class="form-label">Product Name:</div>
<div class="form-field"><input type="text" name="product_name" id="product_name" value="{{ $product_name }}" /></div>
<div class="form-label">Product Price:</div>
<div class="form-field"><input type="text" name="product_price" id="product_price" value="{{ $product_price }}" /></div>
<div class="btn btn-primary"><input type="submit" name="submit" value="Add Product"</div>
</form>
</div>
#include('include/footer')
This is My HomeController.blade.php
public function Edit_Product($id){
return View::make('editproduct')->with('id', $id);
}
public function edit_product_process(Request $request){
$prd_id = $request->pid;
$imageTempName = $request->file('add_image')->getPathname();
$imageName = $request->file('add_image')->getClientOriginalName();
$path = base_path() . '/theme/uploads/';
$request->file('add_image')->move($path , $imageName);
$remember_token = $request->_token;
$date = date('Y-m-d H:i:s');
$pname = $request->product_name;
$pprice = $request->product_price;
DB::table('product')->where('pid',$prd_id)->update(
array(
'pimage' => $imageName,
'pname' => $pname,
'pprice' => $pprice,
'remember_token' => $remember_token,
'created_at' => $date,
'updated_at' => $date,
)
);
return redirect('dashboard');
}
I am getting the below error, Please anyone can be able to help me, I am new at laravel.
page is not found
NotFoundHttpException in RouteCollection.php line 161:

If you're getting this error when you're trying to submit the form, you should check you route. It should look like this:
Route::post('edit-product-process', 'HomeController#edit_product_process');
Also, to pass an ID into edit_product_process you need to add field with ID into the form:
<input type="hidden" name="id" value="{{ $id }}">
And then you can get it in edit_product_process with $request->id

Your route should be as:
Route::get('editproduct/{id}', 'HomeController#Edit_Product')->name('product.edit');
Then you can use it as:
{{ route('product.edit', ['id' => $id]) }}
But it's a terrible practice to use DB queries in views.
Please do read more about queries and controllers in the docs.

Check Your Controller Name Why r using blade in that.This is bad practice.HomeController.blade.php

Related

Update data in laravel 6

I try to create crud in laravel 6. Create, Read and Delete process is running well. But when Update process, the data in table not change. Could anyone help me to find the problem ? The following my code.
Route
Route::get('/blog', 'BlogController#index');
Route::get('/blog/add','BlogController#add');
Route::post('/blog/store','BlogController#store');
Route::get('/blog/edit/{id}','BlogController#edit');
Route::post('/blog/update','BlogController#update');
Controller
public function index()
{
$blog = DB::table('blog')->get();
return view('blog',['blog' => $blog]);
}
public function edit($id)
{
$blog = DB::table('blog')->where('blog_id', $id)->get();
return view('edit', ['blog'=>$blog]);
}
public function update(Request $request)
{
DB::table('blog')->where('blog_id',$request->blog_id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
View
#foreach ($blog as $n)
<form method="post" action="/blog/update" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach
You must provide id in your route
Route::post('/blog/update/{id}','BlogController#update');
In update method add parameter id and then find product against id
public function update(Request $request, $id)
{
DB::table('blog')->where('blog_id',$id)->update([
'blog_title' => $request->title,
'author' => $request->author]);
return redirect('/blog');
}
#foreach ($blog as $n)
<form method="post" action="{{ route('your route name'), ['id' => $$n->id] }}" />
{{ csrf_field() }}
Title <input type="text" name="title" value="{{ $n->title}}">
Author<input type="text" name="author" value="{{ $n->author}}">
<button type="submit" class="btn btn-secondary">Update</button>
</form>
#endforeach
try separating the update into two statements like so
$blog = DB::table('blog')->where('blog_id',$id)->first();
$blog->update([
'blog_title' => $request->title,
'author' => $request->author]);
Also you might want to use models in the future so you can do it like
$blog = Blog::where('blog_id',$id)->first();
Doesn't really shorten your code but it improves the readibility.
Do your update like this:
public function update(Request $request)
{
$post = DB::table('blog')->where('blog_id',$request->blog_id)->first();
$post->blog_title = $request->title;
$post->author = $request->author;
$post->update();
return redirect('/blog');
}

Call to a member function getClientOriginalName() on null when upload image use file system Laravel

I want to upload an image using Laravel storage file system in my admin data. However, there's an error when I attempt to upload an image.
Call to a member function getClientOriginalName() on null
Controller
public function store(Request $request)
{
$admin = $request->all();
$fileName = $request->file('foto')->getClientOriginalName();
$destinationPath = 'images/';
$proses = $request->file('foto')->move($destinationPath, $fileName);
if($request->hasFile('foto'))
{
$obj = array (
'foto' => $fileName,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
}
return redirect()->route('admin-index');
}
View
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
Error
You can check wheather you are getting file or not by var_dump($request->file('foto')->getClientOriginalName());
And make sure your form has enctype="multipart/form-data" set
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
Error because of client Side
<form enctype="multipart/form-data" method="post" action="{{ url('/store')}}">
<div class="form-group">
<label for="" class="col-md-4">Upload Foto</label>
<div class="col-md-6">
<input type="file" name="foto">
</div>
</div>
</form>
you ned to add enctype="multipart/form-data" inside the form
If You are using the form builder version
{!! Form::open(['url' => ['store'],'autocomplete' => 'off','files' => 'true','enctype'=>'multipart/form-data' ]) !!}
{!! Form::close() !!}
Then In your Controller You can check if the request has the file
I have Created the simple handy function to upload the file
Open Your Controller And Paste the code below
private function uploadFile($fileName = '', $destinationPath = '')
{
$fileOriginalName = $fileName->getClientOriginalName();
$timeStringFile = md5(time() . mt_rand(1, 10)) . $fileOriginalName;
$fileName->move($destinationPath, $timeStringFile);
return $timeStringFile;
}
And the store method
Eloquent way
public function store(Request $request)
{
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile= $this->uploadFile($request->foto,$destinationPath );
}
Admin::create(array_merge($request->all() , ['foto' => $fotoFile]));
return redirect()->route('admin-index')->with('success','Admin Created Successfully');
}
DB Facade Version
if You are using DB use use Illuminate\Support\Facades\DB; in top of your Controller
public function store(Request $request)
{
$admin = $request->all();
$destinationPath = public_path().'images/';
$fotoFile='';
if ($request->hasFile('foto'))
{
$fotoFile = $this->uploadFile($request->foto,$destinationPath );
}
$obj = array (
'foto' => $fotoFile,
'nama_admin' => $admin['nama_admin'],
'email' => $admin['email'],
'jabatan' => $admin['jabatan'],
'password' => $admin['password'],
'confirm_password' => $admin['confirm_password']
);
DB::table('admins')->insert($obj);
return redirect()->route('admin-index');
}
Hope it is clear

DOMPDF - Laravel - Email PDF with Attachment

I am getting this error what would be the reason for this
"Undefined variable: quotation"
QuotationController.php
public function update(Request $request, Quotation $quotation)
{
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
}
public function edit(Quotation $quotation)
{
return view('employees.quotations.edit', compact('quotation'));
//return view('employees.quotations.edit')->with('quotation');
}
......................................................................
routes look like this
Route::post('/quotation', 'Employee\QuotationController#store')->name('employee.quotation.store');
Route::get('/quotation', 'Employee\QuotationController#index')->name('employee.quotation.index');
Route::get('/quotation/create', 'Employee\QuotationController#create')->name('employee.quotation.create');
Route::put('/quotation/{quotation}', 'Employee\QuotationController#update')->name('employee.quotation.update');
Route::get('/quotation/{quotation}', 'Employee\QuotationController#show')->name('employee.quotation.show');
Route::delete('/quotation/{quotation}', 'Employee\QuotationController#destroy')->name('employee.quotation.destroy');
Route::get('/quotation/{quotation}/edit', 'Employee\QuotationController#edit')->name('employee.quotation.edit');
employees.quotations.edit.blade.php looks like this
#section('left-menu')
#endsection
#section('right-menu')
#endsection
#section('content')
<h1>Update a Quotation</h1>
<br><br>
<form action="{{ route('employee.quotation.update',$quotation->id) }}" method="post">
#method('PUT')
#csrf
<div class="form-group">
<label for="inputJobDescription">Description</label>
<textarea class="form-control" rows="2" id="inputQuoteDescription" name="description" placeholder="Description">{{$quotation->description}}
</textarea>
</div>
<div class="form-group row">
<label for="inputQty" class="col-2 col-form-label">Qty</label>
<div class="col-10">
<input type="text" class="form-control" id="inputQty" name="qty" value="{{$quotation->qty}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<div class="form-group row">
<label for="inputEachPrice" class="col-2 col-form-label">Each Price</label>
<div class="col-10">
<input type="text" class="form-control" id="inputEachPrice" name="each_price" value="{{$quotation->each_price}}" oninput="quotation_calculate()" onchange="quotation_calculate()">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
#section('pagescript')
#stop
What am i missing here ? I am already passing $quotation to the edit view
You are obviously not passing the $quotation variable through your route. You are also using the $quotation as an object; that tells me you don't intend passing it through the route. Try the following code:
public function update(Request $request, $quotation_id)
{
$quotation = Quotation::findOrFail($quotation_id);
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->update();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message) use ($quotation){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
This should work.
Why are you using double brackets to declare a function ? Why not:
public function update(Request $request, Quotation $quotation)
{
$quotation->description= $request['description'];
$quotation->qty= $request['qty'];
$quotation->each_price= $request['each_price'];
$quotation->save();
$info = ['info'=>$quotation];
Mail::send(['text'=>'mail'], $info, function($message){
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com','John Doe')->subject('Quotation');
$message->from('from#gmail.com','The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});
echo 'Email was sent!';
}
I think you need to pass $quotation into the closure:
Mail::send(['text' => 'mail'], $info, function ($message) use ($quotation) {
$pdf = PDF::loadView('employees.quotations.edit', $quotation);
$message->to('example#gmail.com', 'John Doe')->subject('Quotation');
$message->from('from#gmail.com', 'The Sender');
$message->attachData($pdf->output(), 'filename.pdf');
});

Laravel Pagination Appends Not Keeping Search Data

I've been able to implement the pagination and appends() on my form and it does show the proper values in the url on page 2, though it doesn't actually bring the values back into the form/query, it simply resets the actual data being searched for and displays all.
Here is my form code and the appends.
{{ Form::open(array('class' => 'stdform', 'method' => 'post', 'name' => 'all')) }}
<input type="text" name="srch_lname" class="input-large"
value="{{ Input::old('srch_lname', Session::get('srch_lname')) }}" />
<input type="text" name="srch_fname" class="input-large"
value="{{ Input::old('srch_fname', Session::get('srch_fname')) }}" />
.
.
.
<?php echo $employees->appends(array("srch_lname" => Session::get('srch_lname'),
"srch_fname" => Session::get('srch_fname') ))->links(); ?>
And my Controller
public function getIndex() {
$srch_lname = Session::get('srch_lname');
$srch_fname = Session::get('srch_fname');
$employees = vEmployees::co()->restrictions()
->where('lastname', 'LIKE', $srch_lname . '%')
->where('firstname', 'LIKE', $srch_fname . '%')
->paginate(10);
return View::make('employees.index')
->with('employees', $employees)
->with('title', 'Users');
}
public function postIndex() {
if (Input::has('btnSearch')) {
return Redirect::to('/employees')->with('search', 1)
->with('srch_lname', Input::get('srch_lname'))
->with('srch_fname', Input::get('srch_fname'));
else {
return Redirect::to('/employees');
}
}
Full Form
{{ Form::open(array('class' => 'stdform', 'method' => 'post', 'name' => 'all')) }}
<div class="stepContainer">
<div class="formwiz content">
<h4 class="widgettitle">Search for an Employee</h4>
<p>
<label>Lastname</label>
<span class="field">
<input type="text" name="srch_lname" class="input-large"
value="{{ Input::old('srch_lname', Session::get('srch_lname')) }}" />
</span>
</p>
<p>
<label>Firstname</label>
<span class="field">
<input type="text" name="srch_fname" class="input-large"
value="{{ Input::old('srch_fname', Session::get('srch_fname')) }}" />
</span>
</p>
</div>
</div>
<div class="actionBar" style="text-align: right;">
<button class="btn btn-primary" name="btnSearch" value="1">
Search for Employee(s)
</button>
</div>
{{ Form::close() }}
You need to pass your inputs to the view so that Input::old() has values to work with after the redirect from postIndex to getIndex.
in getIndex(), add to View::make()
->with('input', [ 'srch_lname'=> $srch_lname, 'srch_fname' => $srch_fname ]);
It looks like you do not have the pageSearch value in your pagination query string. Try this.
<?php echo $employees->appends(
array("btnSearch" => "1",
"srch_lname" => Session::get('srch_lname'),
"srch_fname" => Session::get('srch_fname') )
)->links(); ?>
I made a small sample but since I don't have your employees I just used the User model and commented out the filtering, just used as a test to pass and get input values.
Note the change to Input:: from Session, in getIndex() and in the form for $employees->appends(). Use Input instead of Session, I did not see anywhere in your code where you save the filter values in session variables.
I also changed the Redirect::to() to pass the parameters in the URL since it is a get method.
I tested and the filter values are passed to getIndex() and the form fields, also the inputs get properly passed by pagination links.
class EmployeeController extends BaseController
{
public
function getIndex()
{
$srch_lname = Input::get('srch_lname');
$srch_fname = Input::get('srch_fname');
$employees = User::query()
//->where('lastname', 'LIKE', $srch_lname . '%')
//->where('firstname', 'LIKE', $srch_fname . '%')
->paginate(10);
// make input available for page's form fields as old input
Session::flash('_old_input', Input::all());
return View::make('employees')
->with('employees', $employees)
->with('title', 'Users');
}
public
function postIndex()
{
if (Input::has('btnSearch'))
{
return Redirect::to('/employees?search=1&srch_lname=' . urlencode(Input::get('srch_lname')) . '&srch_fname=' . urlencode(Input::get('srch_fname')));
//return Redirect::to('/employees')->with('search', 1)
// ->with('srch_lname', Input::get('srch_lname'))
// ->with('srch_fname', Input::get('srch_fname'));
}
else
{
return Redirect::to('/employees');
}
}
}
Form and ->appends():
{{ Form::open(array('class' => 'stdform', 'method' => 'post', 'name' => 'all')) }}
<div class="stepContainer">
<div class="formwiz content">
<h4 class="widgettitle">Search for an Employee</h4>
<p>
<label>Lastname</label>
<span class="field">
<input type="text" name="srch_lname" class="input-large"
value="{{ Input::old('srch_lname', Session::get('srch_lname')) }}" />
</span>
</p>
<p>
<label>Firstname</label>
<span class="field">
<input type="text" name="srch_fname" class="input-large"
value="{{ Input::old('srch_fname', Session::get('srch_fname')) }}" />
</span>
</p>
</div>
</div>
<div class="actionBar" style="text-align: right;">
<button class="btn btn-primary" name="btnSearch" value="1">
Search for Employee(s)
</button>
</div>
{{ Form::close() }}
<?php echo $employees->appends(array("srch_lname" => Input::get('srch_lname'),
"srch_fname" => Input::get('srch_fname') ))->links(); ?>
I got it working! I continued to do some research and running the search through POST was really a major issue in adding that gap between the search itself and holding the data into the GET method of pagination.
I'll run through everything I did below for anyone in the future having the same issue.
I first created a Route that would direct to a new function in my EmployeesController
Route::get('emp_srch', 'EmployeesController#search');
And created the new function in the Controller
public function search() {
$srch_lname = Input::get('srch_lname');
$srch_fname = Input::get('srch_fname');
$employees = vEmployees::co()->restrictions()
->where('lastname', 'LIKE', $srch_lname . '%')
->where('firstname', 'LIKE', $srch_fname . '%')
->orderBy('lastname')
->orderBy('firstname')
->paginate(10);
Session::flash('_old_input', Input::all());
return View::make('employees.index')
->with('employees', $employees)
->with('title', 'Users')
->with('pagetitle', 'Employees')
}
It's essentially the function I had in the getIndex though rearranging the way the search was functioning I believe was the defining factor in actually getting this to work in my case.
I also changed the url on the form, which directed to my new Route. As well as changing the form so it uses the GET Method and no longer POST.
{{ Form::open(array('url' => 'emp_srch', 'class' => 'stdform', 'method' => 'get')) }}
I do want to thank vladsch and whoacowboy for helping push me in the right direction(s).

Laravel, upload image errors

I know, that there are many many cases about this theme already, but I looked them through, and could not find desired. Also I noticed that not a lot of the users got their answer.
I am working with Laravel5, and I'm trying to upload a picture. Simple upload, just save any picture in public/img folder.
I have looked up some tutorials and came up with this code:
View form:
<form action="{{URL::to('adminPanel/addImg/done/'.$projectId)}}" method="get" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And the controller code:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$filename = $id;
$file->move($destinationPath);
}
I keep getting this error :
Call to a member function move() on a non-object
And I am sure, that the chosen file is image.
I would appreciate any help
So its done, the main issue was the POST part! Also the file format, but here are the correct code, that adds the image:
form:
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}"> //this part is to make POST method work
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
controller:
public function addImageDone($id) {
$file = Input::file('image');
$destinationPath = public_path().'/img/';
$file->move($destinationPath, $id.'.png');
}
I don't know if you are using Laravel 4.2 or 5.0. But..
I recommend you to use illuminate/html - Form class. Try to use POST instead GET to upload files (https://stackoverflow.com/a/15210810/781251, http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1 , http://php.net/manual/en/features.file-upload.post-method.php , http://php.net/manual/en/features.file-upload.php)
If Laravel 4.2:
View:
{{ Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) }}
<label for="file">File</label>
{{ Form::file('file') }}
{{ Form::close() }}
Controller:
public function postImage()
{
if( ( $file = Input::file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return Redirect::back();
}
throw new \Exception('Error while upload file');
}
Laravel 5.0
View:
{!! Form::open(['url'=>'adminPanel/addImg/done' . $projectId , 'files' => true , 'method' => 'POST']) !!}
<label for="file">File</label>
{!! Form::file('file') !!}
{!! Form::close() !!}
Controller:
public function upload(Request $request)
{
if( ( $file = $request->file('file') ) != null && $file->isValid() )
{
$file->move('destination','my_file_new_name.extension');
return redirect()->back();
}
throw new \Exception('Error while upload file');
}
To create a file with a new name and keep the extension:
$ext = $file->getClientOriginalExtension();
$newName = str_random(20) . '.' . $ext;
$file->move( storage_path('images') , $newName );
Now, you have a new name with the same extension. To validate if your file is an image or..whatever, use Validator.
Try this
<form method="POST" action="{!! URL::to('adminPanel/addImg/done/'.$projectId) !!}" accept-charset="UTF-8" enctype="multipart/form-data">
<input name="image" type="file" />
<br><br>
<input type="submit" value="Ielādēt"/>
</form>
And get the image as
public function postImage(Request $request) {
$image = $request->file("image");

Resources