working with Laravel 5.6 and Mysql. and need delete table data using following data.
<td><a class="button is-outlined" href="/student/{{$student->id}}/delete">Delete</a></td>
and Controller delete function is,
public function delete($id)
{
DB::table('students')
->where('id', $id)
->delete();
return redirect()->back();
}
and route is like this,
Route::resource('student','StudentController');
but when click delete button it is generated following error message,
(1/1) NotFoundHttpException
how can fix this problem?
If you use resource controller, you can't generate a link for the DELETE method.
By the way, it's not delete method, but destroy method and link.
The DELETE method expects the request to have DELETE header (like POST, GET or PUT).
The simplest way is to define an URL for you delete method :
Route::get('student/{site}/delete', ['as' => 'student.delete', 'uses' => 'StudentController#delete']);
Or you must use a form like this to call DELETE header :
<form action="{{ route('student.destroy', $studentId) }}" method="POST">
#method('DELETE')
#csrf
<button>Delete</button>
</form>
And you need to change the name of your method :
public function destroy($id)
If you are using Resource Controller you can try this. You can try to DELETE using AJAX Call too.
<td><a class="button is-outlined" id="delete-record">Delete</a></td>
DELETE verb will automatically call destroy action from your Resource Controller.
public function destroy($id)
{
$deleted = DB::table('students')
->where('id', $id)
->delete();
// return number of deleted records
return $deleted;
}
And to perform DELETE use AJAX call like this.
$('#delete-record').click(function(){
$.ajax({
url: '/student/'+{{$student->id}},
type: 'DELETE', // user.destroy
success: function(result) {
console.log("Success");
console.log("No. Of Deleted Records = "+result);
}
});
});
I hope this solution will also work like above one that is already provided.
Related
In this app I have a User table, and a Posts table.
In the individual post blade (post/{id}) I have a button called "Pick Up Task". When clicked, it should set $post->user to the current user's ID. I have set up everything as per the current documentation, yet it still gives me the error: "The POST method is not supported for this route. Supported methods: GET, HEAD."
Here is my code:
Button in Post Blade
<form action="update" method="POST">
#csrf
<input type="hidden" name="user_id" value="{{Auth::user()->id}}"/>
<input type="hidden" name="task_id" value="{{ $task->id }}"/>
<button class="btn btn-outline-secondary" type="submit" value= "UPDATE" href="#">➕ Pick up Task</button>
</form>
Function in the Post Controller
// ADD USER TO TASK
public function update()
{
$user = request('user_id');
$task = request('task_id');
//Fill Post User
$selectedtask = Posts::findOrFail($task);
$selectedtask->update(['user', $user]);
//Success
Session::flash('success', 'You picked up a new task.');
return view('/');
}
My Routes (web.php)
//Add user as assignee
Route::POST('update', 'PostController#update');
try move
Route::POST('update', 'PostController#update');
to top of web.php file, then clear route cache, change code
<form action="/update" method="POST">
(add slash before update) and try your code
You're being sent to the wrong URI.
Change your form tag to this:
<form action="" method="POST">
This will ensure that you are being sent to the exact same route you're currently on, but with a POST method instead of the GET method.
Your routes should look like this:
Route::get('post/{post}', 'PostController#show'); // For viewing
Route::post('post/{post}', 'PostController#update'); // For updating
Correct your update controller method to work with the parameters via model binding:
public function update(Request $request, Post $post)
{
$user = request('user_id');
$task = request('task_id');
//Fill Post User
$selectedtask = Posts::findOrFail($task);
$selectedtask->update(['user', $user]);
//Success
Session::flash('success', 'You picked up a new task.');
return view('/');
}
I'm also assuming that you're mixing up task_id with the ID of a Post model, since you're fetching a post via that request variable? You can, by using model binding and accessing the user via the Request object, boil down your controller method to the following:
public function update(Request $request, Post $post)
{
$post->update(['user' => $request->user()->id]);
return redirect('/')->with('success', 'You picked up a new task.');
}
Model binding will automatically return a 404 if the doesn't exist.
I am having a problem with uri action in laravel.
When I submitted the form, it redirects to the full url if it is successful. But if there is an error, it remains to the current url address.
example:
The current URL is : http://localhost:8000/test?url=test_sample
and my form looks like below:
<form action="{{ url('test?url=action') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="pdf_file">
<input type="submit" name="submit" value="Submit"/>
</form>
If the above form contains an error, it will just remain to test?url=test_sample url. If it is successful, it redirects to test?url=action
EDIT
Controller
class MyFormController extends Controller
{
public function uploadfile(Request $request)
{
$this->validate($request, [
'pdf_file' => 'required|mimes:pdf|max:5000'
]);
return 'uploaded';
}
}
web.php
Route::post('/test', 'MyFormController#uploadfile');
I need this feature to take effect on my site.
Does anybody know?
The URL you're using (http://localhost:8000/test?url=test_sample) contains a url parameter. To use this parameter in the controller, you need to get the value from the $request object injected into the uploadfile() controller method:
$request->get('url');
You can use it to redirect the user from the uploadfile() controller method after processing the upload:
public function uploadfile(Request $request)
{
// ...
return redirect($request->get('url'));
}
Because you're using the validate() method in the controller method, the request will automatically redirect back if the validation fails. You can replace this with manual validation to handle the result yourself:
$validator = Validator::make($request->all(), [
'pdf_file' => 'required|mimes:pdf|max:5000',
]);
if ($validator->fails()) {
return redirect($request->get('url'))
->withErrors($validator)
->withInput();
}
return redirect($request->get('url'));
Edit - I think I misunderstood part of your question. It doesn't look like you want to use the url parameter in the controller method. If not, just change the validation statement.
My EventsController function is this in My Laravel app
public function storetask(Request $request, $id, Task $task)
{
$task = new Task;
$task->task_name = $request->input('name');
$task->body = $request->input('body');
$task->assign = $request->input('status');
$task->priority = $request->input('status');
$task->duedate = $request->input('date');
$task->project_id = $id;
$task->save();
}
I need save form data in My events folder show.blade.php file using above controller function
My form route is this
<form method="post" action="{{ route('events.storetask') }}">
My route.php is this
Route::resource('events', 'EventsController');
but I got this error message
Route [events.storetask] not defined. (View: C:\Users\Flex\Desktop\kuruja\resources\views\events\show.blade.php)
how can solve this?
Define your route like below:
Route::post('/storeTask/{projectId}',array('uses'=>'EventsController#storetask','as'=>'storeTask'));
And call in your view
<form method="post" action="{{ route('storeTask',$yourProjectId) }}">
Replace your controller function with the below function:
public function storetask($id=0)
{
$task = new Task();
$task->task_name = \Input::get('name');
$task->body = \Input::get('body');
$task->assign = \Input::get('status');
$task->priority = \Input::get('status');
$task->duedate = \Input::get('date');
$task->project_id = $id;
$task->save();
}
You need a route for storetask. When you use resource it creates 7 routes you should have on your Events controller. index, create, store, show, edit, update, destroy. You could just direct your form to store or create storetask instead.
You can also use php artisan routes command to view all your routes and you can see there isn't one named storetask.
I think the issue is here:
<form method="post" action="{{ route('events.storetask') }}">
As when you register a resourceful route to the controller like:
Route::resource('photo', 'PhotoController');
This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have methods stubbed for each of these actions, including notes informing you which URIs and verbs they handle.
Actions Handled By Resource Controller
Verb Path Action Route Name
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/{photo} show photo.show
GET /photo/{photo}/edit edit photo.edit
PUT/PATCH /photo/{photo} update photo.update
DELETE /photo/{photo} destroy photo.destroy
but in your case the the method storetask do not match with the above list. So change the name according to the list and try again.
Reference
I need update some record and this is form action in my blade
<form class="form-vertical" role="form" method="post" action="/projects/{{ $project->id }}/collaborators/{{ $collaborator->user()->first()->id }}">
My controller
public function update(Request $request, $projectId, $collaboratorId)
{
$this->validate($request, [
'status' => 'required',
]);
DB::table('permissions')
->where('project_id', $projectId)
->where('collaborator_id', $collaboratorId)
->update(['status' => $request->input('status')]);
return redirect()->back()->with('info','Your Permission has been updated successfully');
}
routes
Route::put('projects/{projects}/collaborators/{id}',['uses'=>'ProjectCollaboratorsController#update',]);
when click update button generate following error
Undefined variable: project (View: C:\Users\Nalaka\Desktop\c\resources\views\collaborators\permissionedit.blade.php)
how to fix this?
With your route Route::put('projects/{projects}/collaborators/{id}',['uses'=>'ProjectCollaboratorsController#update',]); you need to send a PUT request. Your form send a POST request.
Change your route by Route::post or use some javascript to send a PUT request with ajax.
Try that and let's see if there are other error after.
Also, if there are "undefined variable", show the code around this variable.
Aloha, I'm making a workout manager in which you have a dashboard displaying your 5 last workouts. I have set a form for each one workout for allowing the user to delete any of them. Here the form in the dashboard:
{!! Form::open(['route' => ['dashboard.workout.destroy', $workout->id], 'style' =>'display:inline-block;', 'method' => 'DELETE']) !!}
This route will call this method in WorkoutController.php
public function destroy($id, Request $request)
{
$workout = Workout::findOrFail($id);
$workout->delete();
$message = "Workout deleted successfully!";
return redirect()->route('dashboard.index', ['message' => $message]);
}
And this route will call this method in DashboardController.php
public function index($message = null)
{
$user = Auth::user();
// Workouts
...
// Inbodies
...
// Measures
...
return view('dashboard.index', compact('user','workoutsDesc','workouts','lastInbody','inbodies','measures','lastMeasure','message'));
}
The question is that I'm trying to pass the variable $message from WorkoutController to DashboardController for displaying a successfull alert after deleting a workout, but I don't know how to do it. I have tried with:
return redirect()->action('Dashboard\DashboardController#index', [$message]);
return redirect()->action('Dashboard\DashboardController#index')->with('message', $message);
return redirect()->route('dashboard.index', $message);
But I still trying to find the way for doing it.
First of all, from Laravel 5.1 Documentation:
If your route has parameters, you may pass them as the second argument to the route method
As the message is not a parameter to your route, so you can't pass that. A possible solution can be Flashing data. Check the next controller if the session has that key and contain a value, then add it to a variable and pass to the view.
Hope this works.