Trying to delete entries using the destroy method in Laravel controller.
public function destroy($id)
{
$university = University::find($id);
$university->delete();
return redirect('/universities');
}
And this is what i'm using in the view
{!!Form::open(['action' => ['UniversityController#destroy', $university->Id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
Getting no errors and browser redirects after the button is activated as instructed, but the entry still remains in the veiw list and in the DB. Using MySQL.
Posting to the DB also works fine, but having same problems with update method. No errors and get redirected as I should but no update has happened.
public function update(Request $request, $id)
{
$this->validate($request, [
'Name' => 'required',
'Country' => 'required'
]);
$university = University::find($id);
$university->Name = $request->input('Name');
$university->Country = $request->input('Country');
$university->save();
return redirect('/universities');
}
And in view:
{!! Form::open(['action' => ['UniversityController#update', $university->Id], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('Name', 'Name')}}
{{Form::text('Name', $university->Name, ['class' => 'form-control', 'placeholder' => 'Name'])}}
</div>
<div class="form-group">
{{Form::label('Country', 'Country')}}
{{Form::text('Country', $university->Country, ['class' => 'form-control', 'placeholder' => 'Country'])}}
</div>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Submit', ['class' =>'btn btn-primary'])}}
{!! Form::close() !!}
Also tried running without the hidden form methods, but same result.
My routes:
Route::get('/universities', 'UniversityController#index');
Route::get('/universities/create', 'UniversityController#create');
Route::get('/universities/{id}/edit', 'UniversityController#edit');
Route::put('/universities/{id}', 'UniversityController#update');
Route::post('/universities/create', 'UniversityController#store');
Route::delete('/universities/{id}', 'UniversityController#destroy');
Solved by setting public $primaryKey = 'Id'; in the model.
Related
Im trying to use a form to submit reviews for products but I believe the submit button uses the incorrect controller store method. I have a controller for products and one for reviews. The products store works correctly and I can see the database being populated once submitted however when I go to submit a review for a product it will throw the custom error messages from the product store form. If I change the reviews form::open to the products form::open it will throw an error: The PUT method is not supported for this route. Supported methods: GET, HEAD, POST.
Products form (works properly)
{!! Form::open(['action' => 'App\Http\Controllers\ProductsController#store', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
... labels and text ...
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
Reviews form
<div>
<p>Write a review</p>
<!-- submit review form -->
{!! Form::open(['reviews' => 'App\Http\Controllers\ReviewsController#store']) !!}
<div class="form-group">
{{ Form::textarea('description', '', ['class' => 'form-control', 'placeholder' => 'Write your message']) }}
</div>
<div class="form-group">
{{ Form::label('rating', 'Rating') }}
{{ Form::select('rating', ['1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'], '1') }}
</div>
{{ Form::hidden('_method', 'PUT') }}
{{ Form::submit('Submit', ['class' => 'btn btn-primary']) }}
{!! Form::close() !!}
</div>
ReviewsController store
public function store(Request $request, $id)
{
$this->validate($request, ['description' => 'nullable',
'rating' => 'nullable',
]);
$review = new Review;
$review->rating = $request->input('rating');
$review->reviewerid = auth()->user()->id;
$review->productid = $id;
$review->description = $request->input('description');
$review->save();
return redirect('/products/$id')->with('success', 'Review submitted');
}
Web.php file
Route::get('/', 'App\Http\Controllers\PagesController#index');
Route::get('/about', 'App\Http\Controllers\PagesController#abouts');
Route::get('/cart', 'App\Http\Controllers\PagesController#cart');
Route::get('/checkout', 'App\Http\Controllers\PagesController#checkout');
Route::get('/dashboard', 'App\Http\Controllers\PagesController#services');
Route::get('/categories/{Category}', 'App\Http\Controllers\PagesController#category');
Route::resource('reviews', 'App\Http\Controllers\ReviewsController');
Route::resource('products', 'App\Http\Controllers\ProductsController');
Auth::routes();
The error is because of this line:
Form::hidden('_method', 'PUT')
You're telling laravel to use put method. Delete it and it will work fine.
For your form action, I think you have type in this line:
{!! Form::open(['reviews' => 'App\Http\Controllers\ReviewsController#store']) !!}
Change it to :
{!! Form::open(['action' => 'App\Http\Controllers\ReviewsController#store']) !!}
I have created a form which has fillable input fields but there is an option to upload an image to.
The form example:
{!! Form::open(['method' => 'POST', 'route' => ['app.json-ld.update']])!!}
{!! Form::label('name', 'Store name', ['class' => 'form-label']) !!}
{!! Form::text('name', $shop->jsonLDFields->name ?? '', ['class' => 'form-control']) !!}
{!! Form::label('url', 'Store url', ['class' => 'form-label']) !!}
{!! Form::text('url', $shop->jsonLDFields->url ?? '', ['class' => 'form-control']) !!}
{!! Form::label('description', 'Store Description', ['class' => 'form-label']) !!}
{!! Form::textarea('description', $shop->jsonLDFields->description ?? '', ['class' => 'form-
control form-textarea']) !!}
{!! Form::label('telephone', 'Phone number', ['class' => 'form-label']) !!}
{!! Form::text('telephone', $shop->jsonLDFields->telephone ?? '', ['class' => 'form-
control']) !!}
{!! Form::label('image', 'Upload store image', ['class' => 'form-label']) !!}
{!! Form::file('image', (['class' => 'my-1'])) !!}
<button class="btn btn-success my-2" type="submit">Update</button>
{!! Form::close() !!}
Controller:
public function update(Request $request)
{
$shop = Shop::with('jsonLDFields')->first();
$shop->jsonLDFields->update([
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'telephone' => $request->telephone
]);
return back();
I have another controller method which works for uploading, but I don't want to make multiple forms
public function uploadImage(Request $request)
{
$shop = Shop::with('jsonLDFields')->first();
$jsonLd = $shop->jsonLDFields;
if(!$jsonLd) return back();
$request->validate(['image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
$image = $request->image;
$filename = Str::slug(microtime()) . '.' . $image->getClientOriginalExtension();
$request->image->move(public_path('images/json-ld/images'), $filename);
$jsonLd->image = $filename;
$jsonLd->save();
return back();
}
How can I implement an option to upload an image file in update controller method?
Have been trying in different ways, but the result was null.
Would appreciate help with a solution.
Just test if the request input image has file: if($request->hasFile('image')) and if so, than make same steps as in uploadImage()
public function update(Request $request)
$shop = Shop::with('jsonLDFields')->first();
$updateArray = [
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'telephone' => $request->telephone
];
if($request->hasFile('image')){
$image = $request->image;
$filename = Str::slug(microtime()) . '.' . $image->getClientOriginalExtension();
$request->image->move(public_path('images/json-ld/images'), $filename);
$updateArray['image'] = $filename;
}
$shop->jsonLDFields->update($updateArray);
return back();
}
Of course, you should also implement validator ... But for simple example, this should be working.
I've got a form on a Laravel 5.2 application that uses form request validation. When I submit a request and the validator rejects it it goes back to the form and displays the validator's errors. All the user inputs are still there except for the fields that have multi-select, they are cleared. I don't want them cleared, I want them to display what the user had intended.
I'm having a hell of a time trouble shooting this because my localhost version works fine. This problem only occurs on the production version of the application.
Here is the issue request:
class IssueRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [
'do' => 'required|date_format:"F d, Y"',
'issue_advocate' => 'required',
'issue_type_list' => 'required',
'file_stale_date' => 'date_format:"F d, Y"',
'level_of_service_list' => 'required_with:staff_hours',
'issue_outcome_list' => 'required_with:staff_hours',
'staff_hours' => 'numeric',
'date_closed' => 'date_format:"F d, Y"'
];
return $rules;
}
public function messages(){
return [
'issue_type_list.required' => 'Please select at least one issue type.',
'do.required' => 'The date opened field is required.',
'date_format' => 'The :attribute needs to be in the format "January 1, 2000".',
'issue_outcome_list.required_with' => 'Please select at least one outcome before entering staff hours (this marks the issue to be closed)',
'level_of_service_list.required_with' => 'Please select at least one level of service before entering staff hours (this marks the issue to be closed)',
];
}
}
Here is an excerpt of the form. The fields of concern are the issue_type_list, level_of_service_list and issue_outcome_list:
{!! Form::model($issue, array('method' => 'PATCH', 'url' => 'issues/'.$issue->id)) !!}
#include('issues.addIssueForm')
<div class="form-group">
{!! Form::label('issue_type_list[]', "Issue Type") !!}
{!! Form::select('issue_type_list[]', $issuetypes, null, ['multiple' => 'multiple', 'class' => 'form-control multi-select', 'id' => 'issue_type']) !!}
#if($errors->first('issue_type_list'))
<div class="error-item alert alert-danger">{{ $errors->first('issue_type_list') }}</div>
#endif
</div>
{!! Form::hidden('client_id',Input::get('client_id')) !!}
<div class="form-group">
{!! Form::label('level_of_service_list[]', "Level of Service") !!}
{!! Form::select('level_of_service_list[]', $level_of_service, null, ['multiple' => 'multiple', 'class' => 'form-control multi-select', 'id' => 'level_of_service']) !!}
</div>
#include('issues.referralForm')
<div class="form-group">
{!! Form::label('issue_outcome_list[]', "Outcome") !!}
{!! Form::select('issue_outcome_list[]', $outcome, null, ['multiple' => 'multiple', 'class' => 'form-control ']) !!}
</div>
<div class="form-group">
{!! Form::label('staff_hours', "Staff hours") !!}
{!! Form::input('number', 'staff_hours', null, ['class' => 'form-control', 'min'=>'0', 'step' => '0.1']) !!}
</div>
<div class="form-group">
{!! Form::submit('Edit Issue', ['class' => 'btn btn-primary form-control']) !!}
Cancel
</div>
{!! Form::close() !!}
So my create news form is very simple:
<div class="row padding-10">
{!! Form::open(array('class' => 'form-horizontal margin-top-10')) !!}
<div class="form-group">
{!! Form::label('title', 'Title', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="form-group">
{!! Form::label('body', 'Body', ['class' => 'col-md-1 control-label padding-right-10']) !!}
<div class="col-md-offset-0 col-md-11">
{!! Form::textarea('body', null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="col-md-offset-5 col-md-3">
{!! Form::submit('Submit News', ['class' => 'btn btn-primary form-control', 'onclick' => 'this.disabled=true;this.value="Sending, please wait...";this.form.submit();']) !!}
</div>
{!! Form::close() !!}
This is processed by NewsProvider:
public function store()
{
$validator = Validator::make($data = Input::all(), array(
'title' => 'required|min:8',
'body' => 'required|min:8',
));
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
News::create($data);
return Redirect::to('/news');
}
But i have another field, not only title and text body in database, which is author_id and I have no idea how to add info, like the user id from currently authenticated user which wasnt supplied by form. I know how to add hidden input to form with user id, but then someone could change hidden field value. How do I do that correct way?
Maybe I have to edit my news eloquent model in some way, which is:
use Illuminate\Database\Eloquent\Model as Eloquent;
class News extends Eloquent {
// Add your validation rules here
public static $rules = [
'title' => 'required|min:8',
'body' => 'required|min:8',
];
// Don't forget to fill this array
protected $fillable = array('title', 'body');
}
You can always get the current authenticated user by Auth::user(). And you can also modify the $data array before passing it to create. Here's how you do it:
$data['author_id'] = Auth::user()->id;
News::create($data);
Also don't forget to add author_id to the fillable attributes
protected $fillable = array('title', 'body', 'author_id);
I'm not sure why it's not working...
I'm trying to update a user and I keep getting method not allowed error exception.
-- routes
Route::get('superadmin/users', ['as' => 'superadmin.users', 'uses' => 'SuperAdminController#usersIndex']);
Route::post('superadmin/users/{id}', ['as' => 'superadmin.editUser', 'uses' => 'SuperAdminController#editUser']);
-- controller
public function usersIndex()
{
$users = User::all();
return View::make('superadmin.users',compact('users'));
}
public function editUser($id)
{
$user = User::findOrFail($id);
$user->email = Input::get('email');
$user->save();
return Redirect::route('superadmin.users')->with('alertsuccess', 'User has been updated.');
}
-- view
{{ Form::model($user, ['method' => 'PATCH', 'route' => ['superadmin.editUser', $user->id], 'class' => 'form']) }}
<div class="form-group">
{{ Form::label('email', 'Email:', ['class' => 'placeholder-hidden']) }}
{{ Form::text('email', Input::old('email'), ['class' => 'form-control']) }}
</div>
{{ Form::submit('Update User', ['class' => 'btn btn-primary']) }}
{{ Form::close() }}
This is most probably as you need to set up a resource controller in order to use the PATCH method. Try using POST instead.