How to delete a single record in Laravel 5? - php

Using Laravel 5 I m trying to delete a single record within a controller, here is my code:
public function destroy($id)
{
$employee = Employee::find($id);
$employee->delete();
return Redirect::route('noorsi.employee.index');
}
My view page code is:
<td>Delete</td>
My route is:
Route::delete(employee.'/{id}', array('as' => 'noorsi.employee.destroy','uses' => Employeecontroller.'#destroy'));
That did not work.
How do I fix the implementation ?

From the official Laravel 5 documentation:
Delete an existing Model
$user = User::find(1);
$user->delete();
Deleting An Existing Model By Key
User::destroy(1);
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);
In every cases, the number between brackets represents the object ID, but you may also run a delete query on a set of models:
$affectedRows = User::where('votes', '>', 100)->delete();
http://laravel.com/docs/5.0/eloquent#insert-update-delete

So the Laravel's way of deleting using the destroy function is
<form action="{{ url('employee' , $employee->id ) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Employee</button>
</form>
You can find an example here http://laravel.com/docs/5.1/quickstart-intermediate#adding-the-delete-button
And your route should look something like this
Route::delete('employee/{id}', array('as' => 'employee.destroy','uses' => 'Employeecontroller#destroy'));
It works with eg:Route::resource('employee', 'EmployeeController'); and it should also work with how you set up your destroy route.

Obviously you have a bad routing problem. You're trying to use a 'get' verb to reach a route defined with a 'delete' verb.
If you want to use an anchor to delete a record, you should add this route:
Route::get('/employee/{id}/destroy', ['uses' => 'EmployeeController#destroy']);
or keep using a delete verb, but then you need to use a form (not an anchor) with a parameter called _method and value 'delete' stating that you're using a 'delete' verb.

Route::get('/showcon/{del_id}/delete','MainController#deletemsg');
public function deletemsg($del_id){
$mail=Mail::find($del_id);
$mail->delete($mail->id);
return redirect()->back();
}
del

Related

Laravel 5.4 update method

I am trying to update the record in the database. This is a specific element that is an element of another. Here is my code, it doesnt work :/
web.php :
Route::patch('/projects/{projectID}/{id}', 'ProjectsController#update');
Controller:
public function update($projectId, $id, CreateProjectRequest $request)
{
$page = Page::findOrFail($id);
$page->update([
'name' => $request->name,
]);
return redirect('/projects/' . $projectId);
}
HTML:
{!! Form::model($page, ['method'=>'PATCH', 'action' => ['ProjectsController#update', $project->id, $page->id]]) !!}
{!! Form::text('name',null,['class'=>'blue-inp']) !!}
{!! Form::submit('Save changes',['class'=>'btn btn-save-blue']) !!}
{!! Form::close() !!}
You need to switch the class type-hint CreateProjectRequest for just Request in your controllers update method.
The variables passed from the form input fields can then be accessed like this:
$name = $request->input('name');
More on the topic: https://laravel.com/docs/5.0/requests
You can simplify the controller method, assuming the CreateProjectRequest handled all the necessary validation and it's inputs match the inputs you want to update
Edit: I prefer to validate everything with formrequests with rules and by the time it reaches the controller, it just calls services or does stuff.
As far as naming conventions, you may not need to send the $id in the url parameter and send it within the body, in order to avoid using Request in the formrequest to validate if it exists in the database
public function update($projectId, $id, CreateProjectRequest $request)
{
$data = $request->validated();
Page::findOrFail($id)->update($data);
return redirect('/projects/' . $projectId);
}

Update a value in a destroy method in Laravel

I make a clone system in Laravel. I want to clone activities.
When I click on "Clone", my line is cloned and receives as the value in the column "parent_id" the ID of the original.
The original gets a value of 1 in the "hasClone" column.
But when I want to delete a clone, in my destroy method, I try to set hasClone (the original entry) to NULL before deleting the clone.
Here is my code :
public function destroyChanges(Activity $activity)
{
$parentActivity = Activity::findOrFail($activity->parent_id)->first();
$parentActivity->hasClone = NULL;
$parentActivity->save();
$activity->delete();
return redirect()->to('/admin/activity/');
}
Here is my route :
Route::delete('activity/destroyChanges/{id}', ['as' => 'cancel.activity', 'uses' => 'ActivityCrudController#destroyChanges']);
Here is my button :
{{ Form::open([ 'method' => 'DELETE', 'route' => [ 'cancel.activity', $entry->getKey() ] ]) }}
<button class="btn btn-default"><i class="fa fa-ban"></i> {{ trans('backpack::crud.cancel') }}</button>
{{ Form::close() }}
The entry of the clone is deleted correctly. But he does not update the original entry. How to do ? thank you very much
EDIT : I also tried that :
public function destroyChanges($id)
{
$activity = Activity::findOrFail($id);
$parentActivity = Activity::where('id', '=', $activity->parent_id)->first();
$parentActivity->hasClone = NULL;
$parentActivity->save();
$activity->delete();
return redirect()->to('/admin/activity/');
}
Even if I put a die (); in the destroy method, he ignores it. Why does not it take it into account?
You need to define parent method in your model and access the parent like the best answer in the following toppic:
How to implement a self referencing (parent_id) model in Eloquent Orm
when you access to that can change hasClone field and save that before the update.
Like this:
$parentActivity = $activity->parent()->first();
$parentActivity->hasClone = null;
$parentActivity->save();
Ensure to have something like this in your activity model:
public function parent()
{
return $this->belongsTo('Activity', 'parent_id');
}

ErrorException Missing required parameters laravel

I am having an issue by modifying the route for a view. I want instead of /company/id to show /company/id/name
the route:
Route::get('/company/{id}/{name}', 'PagesController#showCompany')->name('company.detail');
show method in controller:
public function showCompany($id){
$company = Company::find($id);
return view('company.show')->with('company', $company);
}
and in the view $companies is from a search controller - and it should get the results with a link to open the view
#foreach($companies as $company)
Show detail
#endforeach
if using only with id like /company/id works. What i am wrong?
A simple an elegant way (i think) is:
{{route('company.detail', ['id' => $company->id, 'name' => strtolower(preg_replace('/[^A-Za-z0-9-]+/', '-', $company->company_name))}}
You can have a friendly url name. I am sure that there are better solutions out there.
If you have more params in the route you can use an associative array and initialize each param name with a value.
the controller now is the same with the id.

Laravel - delete specific post from logged in user

I'm trying to make a delete button on a post from a user that is logged in. The logged in user can see other peoples posts, and only delete his own. I already managed that the delete button only appears on his own posts. I think the problem is in the route in the view..
Controller:
public function destroy($id)
{
$post = Post::find($id);
$post->delete;
return view('/home', [
'posts' => $post
]);
}
view:
#if ($post->checkUser(Auth::user()))
<form action="{{ route('posts.destroy, $post') }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete</button>
</form>
#endif
Route:
Route::resource('posts', 'PostController');
Change $post->delete; to $post->delete(); because delete() method is a function. And if you use resource you should send request with delete method for call destroy method. but you can not do it from form because for support only post and get, another solution you can use hidden input and send with post method, <input name="_method" type="hidden" value="DELETE">
You need to specify post_id and user_id both.
public function destroy($id)
{
$user_id = Auth::user();
$post = Post::where('post_id', $id)->where('user_id',$user_id)-get();
$post->delete();
// do your rest of code
}
Change post_id and user_id name according to your table field name.
I think you should edit the route in your view to look like this,
route('posts.destroy, ['id' => $post->id]'), if that doesn't work check your named route again by doing php artisan route:list, and also try to post the full error for better understanding.

how we can pass multiply id in laravel

My view.blade.php code here
<a href="{{ url('p_grid') }}/{{($cat_id)}}/{{$row->sub_id}}">
My route code here
Route::resource('p_grid', 'BasicController#p_grid');
And my BasicController code here
public function p_grid(Request $request, $id)
{
echo "success";
if ($id == 1) {
$r = DB::table('sub_category')
->select('*')
->where('cat_id', $id)
->where('sub_status', '1')
->orderBy('sub_id', 'asc')
->get();
$cat_name = DB::table('category')
->where('cat_id', $id)
->get();
$count = DB::table('products')
->where('sub_id', $id)
->count();
return view('buy-and-sell/p_grid', compact('r','cat_name','count','id'));
}
click on anchor tag to show this error
The extra parameter in your URL is causing the 404. Laravel doesn't expect the URL to have multiple id's, because you are using resourceful routing. You will need to append your routes.php file to account for this:
Route::resource('p_grid', 'BasicController#p_grid');
Route::get('p_grid/{category}/{subcategory}', [
'as' => 'category-with-subcategory',
'uses' => 'BasicController#gridWithSubcategory',
]);
And make sure you have a gridWithSubcategory method in your BasicController.php file.
That said, I'd advise you to understand better what Laravel is doing when you declare Route::resource(), because I would question how much of it you really need. It's really just a shorthand for registering ordinary routes (see here for the full list and specifications) like index, create, show, destroy, etc. If you want to see the routes your app actually has, after being parsed by Laravel (including routes not in your routes.php, which could have been registered by third-party packages) type php artisan route:list on a CLI.
Finally, I'd strongly suggest using route names throughout your app for better clarity and portability. The artisan command above will give you route names, so you can use something like this in your views:
<a href="{{ route('category-with-subcategory', ['category' => $cat_id, 'subcategory' => $row->sub_id]) }}">
That way, if you ever want to change your route's footprint, the view won't break (as long as you maintain the parameter requirements).
My view.blade.php code here
<a href="{{ url('p_grid', ['category' => $cat_id, 'subcategory' => $row->sub_id]) }}">
My route code here
Route::get('p_grid/{category}/{subcategory}', [
'as' => 'category-with-subcategory',
'uses' => 'BasicController#p_grid'
]);
And my BasicController code here
public function p_grid(Request $request, $id)
{
echo "success";
}
success image upload and work done
enter image description here

Categories