Laravel Search Delete - laravel

When I make search and I get the search results, I try to delete a record , its deleted show the message that successfully deleted but after I get the error throw new MethodNotAllowedHttpException($others);
public function destroy($id)
{
$id = Hashids::decode($id);
$id = implode(',', $id);
$sub = Subs::find($id);
$sub->delete();
return response()->json([
'success' => "Subscription Plan Deleted successfully.",
'tr' => 'tr_' . $id,
]);
}
The routes:
Route::post('/subscriptions/search/results','SubsController#searchSubs');
Route::get('/subscriptions/restore/{id}', 'SubsController#restore');
The link:
<a href="{{action('SubsController#destroy', Hashids::encode($sub['id']))}}" class="btn btn-danger btn"
data-tr="tr_{{$sub['id']}}" data-toggle="confirmation" data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
data-btn-ok-class="btn btn btn-danger" data-btn-cancel-label="Cancel"
data-btn-cancel-icon="fa fa-chevron-circle-left" data-btn-cancel-class="btn btn btn-default"
data-title="Are you sure you want to delete ?" data-placement="left" data-singleton="true">Delete </a>

Route::resource('subscriptions','SubsController');
creates a destroy method which requires request type DELETE.
e.g.
Route::delete(subscriptions/destroy','SubsController#destroy');
to do so you will have to make a form and send a DELETE request like below.
<form action="{{ route('routename',$parameter) }}" method="POST">
{{csrf_field()}}
{{method_field('DELETE')}}
<button type="submit" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill"> <i class="glyphicon glyphicon-trash"></i></button>
</form>
check your route in console by
php artisan route:list
If you cant do that then:
remove destroy method from resource like this:
Route::resource('subscriptions','SubsController')->except('destroy');
Now it will not include destroy method. Now you can make your own route of get request and send id of record to delete it

Related

Laravel select field validation

I am currently building a feature where a user can select an option from a select box, once an item is selected you can click a button which hits my endpoint which submits and stores it.
However if i dont select anything but then click the button it just hits a 404 page on the same endpoint.
Blade
Below contains the blade syntax for the select box and button.
<div class="row align-items-center">
<div class="col-md">
<small class="text-success">
please select one of the teams below to store your preference.
</small>
{!! Form::open(['route' => ['team.create.link', $team->id],'method' => 'post', 'class' => 'needs-validation','novalidate', null]) !!}
{!! Form::select('teams[]', $teams, '', ['class' => 'custom-select', 'multiple'], ['required']) !!}
<button class="btn btn-primary btn-sm mt-3 float-right">
<i class="fas fa-fw fa-plus-circle mr-2"></i>
Add</button>
{!! Form::close() !!}
</div>
</div>
Method
Below is the method used for storing the new input within the pivot table.
public function link(string $teamId)
{
$team= Team::findOrFail($teamId);
$links = Input::get('teams');
$link = Team::findOrFail($links);
$team->links()->attach($link);
session()->flash('success', 'Link Added.');
return back();
}
Help
How would i modify this so that the button cant be clicked and returns a required error if an option isnt selected? i've tried adding ['required'] to the form::select but i had no luck with that.
Can anyone push me in the right direction?
You can validate your Reqeust with $this->validate
use Illuminate\Http\Request;
public function link(Request $reqeust, string $teamId)
{
$request->validate([
'teams' => 'required',
]);
$team = Team::findOrFail($teamId);
$links = Input::get('teams');
$link = Team::findOrFail($links);
$team->links()->attach($link);
session()->flash('success', 'Link Added.');
return back();
}
Take a look at the official Laravel Documentation for Validation

Yajra Ajax Datatables Including Dynamic URL with parameter

I am using Yarja datatables for quite a complex table set and also have the ajax part returning two buttons:
{
$user = Auth::user();
$cl = $user->client_id;
$jb = DB::table('job')
->join('job_status', 'job.jobStatus_id', '=', 'job_status.id')
->join('customers', 'job.customer_id', '=', 'customers.id')
->join('users', 'job.operative_id', 'users.id')
->where('job.client_id', $cl)
->select(['job.id as id', 'job_status.status as status', 'job.customer_id as customer_id', 'customers.customer as customer', 'users.name as operative','job.address as address','job.postcode as postcode','job.slug as slug','job_status.id as jobStatusID'])
->get();
return Datatables::of($jb)
->addColumn('action', function($pubs){
$btn = '<div style="float:right">
<i class="fas fa-book" ></i><i class="fas fa-edit" ></i></div>';
return $btn;
})
->make(true);
}
This works fine but now I want to add an action to the buttons, initially the edit, which is the route and the id of the row.
As you can see I have replaced the # with the route so I have
"admin\jobView"
but I cannot seem to work out a way of adding a field from the query (specifically jb->id) so that the action would be something like
admin\jobView\123
Just can't seem to get it and would greatly appreciate some help!
$pubs should contain your job, so you should be able to use $pubs->id, to get the job id.
What I would do though is replace this giant string with a view so it becomes easier to maintain:
return Datatables::of($jb)
->addColumn('action', function($job) {
return (string)view('admin.jobs.action', compact('job'));
})
->rawColumns(['action'])
->make(true);
Create a view, admin/jobs/action.blade.php for example:
<div style="float:right">
<a href="{{ route('admin.jobview', $job->id) }}" class="btn btn-outline-secondary btn-xs" title="show details" style="margin-right:.5em;font-size:.75em">
<i class="fas fa-book"></i></a>
<a href="{{ route('admin.jobview', $job->id) }}" class="btn btn-outline-secondary btn-xs" title="show details" style="margin-right:.5em;font-size:.75em">
<i class="fas fa-edit"></i>
</a>
</div>

POST method not supported for route in Laravel 6

I am building a discussion form in Laravel 6. The route I used is a POST method and I checked it in route:list. I get the following error, why?
The POST method is not supported for this route. Supported methods:
GET, HEAD, PUT, PATCH, DELETE
View
<form action="{{ route('replies.store', $discussion->slug) }}" method="post">
#csrf
<input type="hidden" name="contents" id="contents">
<trix-editor input="contents"></trix-editor>
<button type="submit" class="btn btn-success btn-sm my-2">
Add Reply
</button>
</form>
Route
Route::resource('discussions/{discussion}/replies', 'RepliesController');
Controller
public function store(CreateReplyRequest $request, Discussion $discussion)
{
auth()->user()->replies()->create([
'contents' => $request->contents,
'discussion_id' => $discussion->id
]);
session()->flash('success', 'Reply Added.');
return redirect()->back();
}
You passed a disccussion object as parameter in order to store user_id within an array.
I think this is not a good practice to store data.
You might notice that your routes/web.php and your html action are fine and use post but you received:
"POST method not supported for route in Laravel 6". This is runtime error. This probably happens when your logic does not make sense for the compiler.
The steps below might help you to accomplish what you want:
1. Eloquent Model(App\Discussion)
protected $fillable = ['contents'];
public function user(){
return $this->belongsTo('App\User');
}
2. Eloquent Model(App\User)
public function discussions(){
return $this->hasMany('App\Discussion');
}
3. Controller
use App\Discussion;
public function store(Request $request){
//validate data
$this->validate($request, [
'contents' => 'required'
]);
//get mass assignable data from the request
$discussion = $request->all();
//store discussion data using discussion object.
Discussion::create($discussion);
session()->flash('success', 'Reply Added.');
return redirect()->back();
}
4. Route(routes/web.php)
Route::post('/replies/store', 'RepliesController#store')->name('replies.store');
5. View
<form action="{{ route('replies.store') }}" method="post">
#csrf
<input type="hidden" name="contents" id="contents">
<trix-editor input="contents"></trix-editor>
<button type="submit" class="btn btn-success btn-sm my-2">
Add Reply
</button>
</form>

How to update column in database in blade.php file Laravel

Hello I have row in a database table have an id and name and etc.. and active = 1
I want in blade.php file when someone click a button it change into 0 in 1 click
What I tried is {{$referral_detail->update('active', 1)}}
And
{{$referral_detail->IDT->where('active', 0)->update('active', 1)}}
Function in Controller is
public function DriverReferAll()
{
$query = DriverReferralDiscount::where([['referral_driver_id', '!=', 0],
['referral_sender_id', '!=', 0], ['active', '<>', 1]
]);
$referral_details = $query->paginate(25);
return view('merchant.driver.driver_referall', compact('referral_details', 'query'));
}
I got it thedit('{{$referral_detail->IDT->update(['active' => 1])}}')
and function
function thedit(a) {
$("input:submit").val(a);
}
But when I do it , it change the first 2 column not only 1 tho I put the specific id any idea?
its in onClick""
<span onClick=" thedit('{{$referral_detail->IDT->update(['active' => 1])}}')
" data-target="#addMoneyModel"
data-toggle="modal" id="{{ $referral_detail->GetterDriver->id }}"><a
data-original-title="Add Money"
data-toggle="tooltip"
id="{{ $referral_detail->GetterDriver->id }}" data-placement="top"
class="btn text-white btn-sm btn-success menu-icon btn_detail action_btn"> <i
class="fa fa-money-bill"></i> </a></span>
For that you must create a link in your blade template when that link is clicked It must have an href which point to the laravel route which will perform the update of your active state.
<a href="{{ route('your_route_name', ['id' => $referral_detail->id]) }}>Change</a>
the route can be define like this
Route::get('/route_path/{id}', 'ControllerName#action_name')->name('route_name');
Or If you want the browser to not refresh you can perform and Ajax

Delete A Record From A Relationship

I want to delete a record: remove a routine,that belongs to a user, on button click (hasMany). I have set up the view, models and relationship within,delete route, and the controller method to delete.
When I try to click the button to remove the routine from the db, it does nothing. why does it not removing the record?
Here's my code: route:
Route::post('routine/delete', 'RoutineController#delete'); // Delete a routine for a user.
Controller:
public function delete(Request $request)
{
$id = $request->input("id"); // Getting the id via. the ajax request.
$routine = \App\Routine::find($id); //Fetching the routine object from the db ifentified by the id passed via ajax
if ($routine)
{
$routine->delete();
}
return ["status" => "success"];
}
View:
<div class="col-lg-2">
<!-- When this button is clicked, we determine which routine to remove. -->
<button class="btn btn-danger remove_routine" data-id="{{$routine->id}}" data-token="{{csrf_token()}}" style="display:inline">Delete</button>
</div>
User Model:
public function routine()
{
return $this->hasMany('App\Routine');
}
Routine model:
public function user()
{
return $this->belongsTo('App\User');
}
Thanks in advance!
Don't know if it exactly answers your question, and I don't use AJAX, but I always do my deletes like this:
View
#foreach($database-thing as $item)
<form method="POST" action="$yourActionHere" style="display:inline" >
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger btn-xs"><i class="fa fa-trash"></i> Delete</button>
</form>
#endforeach
// Even easier with laravelcollective/forms
#foreach($database-thing as $item)
{!! Form::open([
'method'=>'DELETE',
'url' => [$yourUrl, $item->id // <-- Very important],
'style' => 'display:inline'
]) !!}
{!! Form::button('<i class="fa fa-trash"></i> Verwijder', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs']) !!}
{!! Form::close() !!}
#endforeach
Controller
public function destroy($id)
{
YourModel::destroy($id);
// All your other logic like redirects and stuff
}
Working delete, based on the code above and this updated controller function:
public function delete(Request $request,$id)
{
$user=Auth::user();
$routine = \App\Routine::findOrFail($id); // find or throw an error if you don't find the routine id in db.
// Makes if() statement redundant, since it checkes for that id already.
// Need to check that the owner of the routine is the current authenticated user.
if ($user->id != $routine->user->id)
{
Session::flash('flash_message', 'No routine found.');
}
else
{
$routine->delete();
Session::flash('routine_deleted','Routine deleted!');
}
// No need to return $routine since I am deleting it, otherwise it will throw and error of trying to get property of non-object.
return redirect()->back()->with('user') ;
//return view('view_routine')->with('user', 'routine');
}
There you go
$remove = 2;
$filtered = $c->filter(function ($value, $key) use($remove){
return $value['id']!=$remove;
});

Resources