How to delete data from database in Laravel 8.* - php

I'm trying to delete city from my db but i really got no clue what to do next.
Since I didnt find anything about deleteing data from db for Laravel 8.* I think this might be usefull for other stackoverflowers too.
My error says clearly that I'm missing some arguments,
Too few arguments to function App\Http\Controllers\CityController::delete(), 0 passed in C:\xampp\htdocs\Laravel1\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 1 expected
While my controller says that he expected type 'object' but only found array
Exoected type 'object'. Found 'array'. intelephense(1006)
#var array $todelete
Here is Route from web.php
Route::delete('cities', [App\Http\Controllers\CityController::class, 'delete'])->name('cities.delete');
And this is form I'm using to delete
<form class="float-right m-0" method="post" action="{{ route('cities.delete') }}">
#method('delete')
#csrf
<div class="form-row">
<input type="hidden" name="cityId" value="{{ $city->id }}">
<button> <i class="fa fa-trash-alt"></i></button>
</div>
</form>
Edit
After solving previous problems, I'm stuck on another error:
Call to a member function delete() on array
Here is how my "CityController"s function looks like after updates
public function delete(Request $request)
{
$cityId = $request->get('cityId', false);
// TODO: Check for validation
$todelte = DB::select('select '.$cityId.' from cities');
$todelte -> delete();
return redirect('frontend/city/index');
}
Correct query to delete stuff:
DB::table('cities')->where('id', $cityId)-> delete();

The issue with not getting the $id parameter passed has to do with your route not accepting any parameters.
Your call is DELETE /cities, which does have any parameters.
If you changed that to DELETE /cities/5, than you could get a parameter passed down the line.
In order to get the parameter to your controller you should change your route as follows:
Route::delete('cities/{id}', [App\Http\Controllers\CityController::class, 'delete'])->name('cities.delete');
This way the {id} part will be passed along to the function specified in the callback. To make your form work with that new route you should change the action-part of you form to direct to the new URL.
I suggest using the 2nd parameter as well so you get:
route('cities.delete', ['id' => $city->id])
Then you can remove the hidden input.
If you do want to keep the existing form you need to use the Request as a parameter in your delete-function. That would look like this:
public function delete(\Illuminate\Http\Request $request)
{
$cityId = $request->get('cityId', false);
// TODO: Check for validation
$todelte = DB::select('select '.$cityId.' from cities');
$todelte -> delete();
return redirect('frontend/city/index');
}

Related

Laravel Model not loaded with data when trying to delete

I have one link as below:
<a href='{{ route('transferDelete', $tran->transfer_id) }}'><i class='far fa-trash-alt'></i></a>
It gets parsed by the following route:
Route::get('delete/{transfer_id}', [TransferController::class, 'destroy'])->name('transferDelete');
But the destroy method in the TransferController class is empty. On the other hand, the second parameter gets the correct ID (as expected):
public function destroy(Transfer $transfer, $bla)
{
//$transfer behaves like: $transfer = new Transfer;
//$bla is a real id.
}
Is there a way to make $transfer be pointing to transfer_id=$bla, without explicitly doing a Transfer::find($bla)?
You need to match the route parameter name to the name of the typehinted parameter of the Controller method if you want Implicit Route Model Binding to take place:
v
Route::get('delete/{transfer}', ...);
v
public function destroy(Transfer $transfer, $bla)

Symfony 5 Delete methods, Unable to guess how to get a Doctrine instance from the request information for parameter

I wanted to put in my controller a second delete button to delete comments but I got lots of error messages like the one from ParamConverter because it did not recognize the class.
So in my controller I have a ParamConverter like this:
/**
* #Route("/delete/{comment_id}", name="comment_delete", methods={"DELETE"})
* #ParamConverter("comment", class="App:Comment", options={"id": "id"})
*/
public function deleteComment(Request $request, BlogPost $blogPost, Comment $comment, $comment_id): Response
{
if ($this->isCsrfTokenValid('delete' . $comment->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($comment);
$entityManager->flush();
return $this->redirectToRoute('/');
}
return $this->render('comments/_delete_form.html.twig', [
'comment' => $comment
]);
}
In my twig, I added this:
<form method="post" action="{{ path('comment_delete', {'comment_id': comment.id}) }}" onsubmit="return confirm('Are you sure you want to delete this item?');">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token('delete' ~ comment.id) }}">
<button class="btn delete">Delete</button>
</form>
But it creates an error message:
"Unable to guess how to get a Doctrine instance from the request information for parameter" comment ".
Usually, Symfony will try to convert the route parameters to entities automatically if you typehint them in the function signature. For example, since you don't use the BlogPost entity, you could just write:
/**
* #Route("/delete/{id}", name="comment_delete", methods={"DELETE"})
*/
public function deleteComment(Comment $comment): Response
You should change the parameter name in your twig function too, of course.
If you want to be more explicit and keep the parameter name as is, for clarity, you can write:
/**
* #Route("/delete/{comment_id}", name="comment_delete", methods={"DELETE"})
* #ParamConverter("comment", options={"id" = "comment_id"})
*/
In order to map the route argument to the column name.
The error you are receiving is because you wrote options={"id": "id"} telling the converter to look up the entity by using the id parameter in the url, and of course there's no id parameter.

routes laravel with a variable

Hello this is my controller:
public function getValues(Request $request){
$typ=$request->get('typ');
$stellentyp=$request->get('stellentyp');
$bereich=$request->get('bereich');
$view = 'user.'.$stellentyp;
return view($view,['typ' => $typ, 'stellentyp', $stellentyp, 'bereich', $bereich]);
}
I want that the user can select a "stellentyp" and then the view with that "stellentyp" should be shown.
But I have a problem with my routes, they do not know the variable "stellentyp".
How can I connect my controller with my routes?
I tried this
Route::post('user/{$stellentyp}', 'StartController#getValues')->name('user.{$stellentyp}');
but it does not work :(. The error is:
Missing required parameters for [Route: user] [URI:
user/{$stellentyp}]. (View:
C:\xampp\htdocs\j4ylara\resources\views\user\start.blade.php)
Route::post('user/{stellentyp}', 'StartController#getValues')->name('user.values');
In order to add a variable inside the route path you don't have to use the dollar signal to declare it. Check above code. Also the name of the route does not have to be dynamically assigned.
in laravel routes you don't need $ sign for variable
, remove $ sign and test your route again, it should be work...
Route::post('user/{stellentyp}', 'StartController#getValues')->name('user.stellentyp');
and add $stellentype to your controller method input like that:
public function getValues(Request $request,$stellentype)
Route parameter totaly different from POST parameters.
when you send a post parameter, it should be in your form as a input or selectbox etc.. then you can catch them in controller with get() method from $request (instance of Request class)
public function getValues(Request $request){
$request->get("post")
}
But route parameter not send in a form, we send them with below way
in blade file
<form action="{{route("user.values",$user_id)}}">
in route file
Route::post('user/{id}', 'StartController#getValues')->name('user.{$stellentyp}');
and catch them in controller as a function parameter
public function getValues(Request $request,$user_id){
dd($user_id);
}
i get it :D
<form action="{{ action('StartController#getValues') }}" method="post" id="postData">
{{ csrf_field() }}
<select name="stellentyp">
<option value="praktika">Praktika</option>
<option value="fwd">Freiwilligendienste</option>
<option value="jobs">Ferien- und/oder Nebenjobs</option>
</select>
<button type="submit">Jetzt finden</button>
this is my blade.php
and my controller is the same and my routes looks like this
Route::resource('user/start', 'StartController');
Route::post('user/angebote', 'StartController#getValues');
Route : -
Route::post('user/{stellentyp}', 'StartController#getValues');
Controller : -
public function getValues(Request $request,$stellentyp=''){
$typ=$request->get('typ');
$stellentyp=$request->get('stellentyp');
$bereich=$request->get('bereich');
$view = 'user.'.$stellentyp;
return view($view,['typ' => $typ, 'stellentyp', $stellentyp, 'bereich', $bereich]);
}
Use this code to get the expected answer.

Laravel - How to pass variable from middleware to controller

I'm trying to pass a token from middleware to view and controller. But all the steps I've tried:
Laravel - Passing variables from Middleware to controller/route
Pass variable from middleware to templates
Pass variable from middleware to view via controller in Laravel 5.2
Haven't helped much. Here is my setup:
Requests come in the form of:
https://website.com/reviews?linker=129b08e19014420049da7d6d7aa8fc35fc6279c4
Then gets parsed and checked by middleware:
Middleware
class CheckReviewLink
{
/**
* Check Review Link - granting clients access to submit review
* =================
* Check that user's link matches the 40 character string generated for user
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$url = $_SERVER['REQUEST_URI'];
$parts = parse_url($url);
$data['token'] = parse_str($parts['query'], $query);
$testimonies = Testimony::all();
foreach ($testimonies as $testimony) {
if ($query['linker'] == $testimony->token) {
Session::flash('token', $data);
return $next($request);
}
}
}
}
** View **
<div class="col-lg-6">
<article>
<input disabled type="text" placeholder="{{Session::get('token', $data)}}" id="token" name="token" size="100" class="form-control border-form white font4light">
</article>
</div>
When I go to get the session data within my view/controller, I get the error:
Undefined variable: data
Any ideas anyone?
Session flash storage is for retaining data between execution times of the application, ie passing from one page load to the other. In your case you are only wanting to pass data from one part of the app to the other during a single run, thus vars in the memory will be cleaner and quicker.
This guy answered it already: Laravel Middleware return variable to controller
You now have better and clearer control of the code and can pass through to, if required, your data to the views and don't have to worry about clearing up your old session data.
First of all you don't need first line in your handle method. You aren't using $response variable.
Secondly use $request->url() instead of $_SERVER['REQUEST_URI'].
And your answer is to simply use session('token') to gat token you want.
If you want to retrieve a session data, you just have to call the session() helper method, and give it the key of the data that you want:
$myToken = session('token');
But, in your case, your are storing an associative array to the session, so when you call it, you have to do like this:
$myToken = session('token')['token'];
So in your view, you will end up with:
<div class="col-lg-6">
<article>
<input disabled type="text" placeholder="{{ session('token')['token'] }}" id="token" name="token" size="100" class="form-control border-form white font4light">
</article>
</div>
You don't need to use a variable when you're trying to get data from the session. So, do this instead:
{{ Session::get('token') }}
Or simply:
{{ session('token') }}
Also, instead of flash() method do this:
session(['token' => $data]);
And then delete it manually if needed:
session()->forget('token');

How to pass id value from select list to controller when controller expects an object? laravel-4

I've constructed a select list in a dashboard view, which lists id and name of various components. The data is passed to a controller that makes a view using the passed id to pull up the correct component data for that id. Problem is that the controller is constructed to expect an object from which to get the id, so that when I submit the id from the list, I get a "Trying to get property of non-object" error. (It doesn't matter whether I submit to the route or directly to the controller; I get the same error.) Here's the code:
PagesController (that creates list array for the dashboard):
public function showDashboard()
{
$components = Component::lists('name','id');
return View::make('dashboard', array(
'components'=>$components, ...
));
}
Snippet of source code for the select list:
<form method="GET" action="https://..." accept-charset="UTF-8">
<select id="id" name="id"><option value="2">Component Name</option>...
Components Model:
class Component extends Eloquent {
protected $table = 'components'; ... }
ComponentsController:
public function show($id)
{
$component = $this->component->find($id);
return View::make('components.show', array(
'component'=>$component, ...
));
}
dashboard.blade.php:
{{ Form::open(array(
'action' => 'ComponentsController#show',
'method'=>'get'
)) }}
{{ Form::Label('id','Component:') }}
{{ Form::select('id', $components) }}
{{ Form::close() }}
The same controller code is used for other purposes and works fine, for example, when I pass a specific id from a URL, it accepts that id without an error. So, I know this should be something simple involving the form opening, but I can't figure it out. How can I fix this? Thanks!
It will not work because using get method the url will be like this.
http://laravel/puvblic/show?id=2
and laravel will not accept it , rather it accepts a parameter for function in this way
http:/laravel/puvblic/show/2
A better way to do this would be to make your form method as 'POST' . It would be much safer and better this way. and modify your function as.
public function show()
Then , You can get the id in your controller as
Input::get('id')
EDIT:
To make it simple , try this one:
Route::get('{show?}', function()
{
$id = Input::get('id') ;
echo $id; //This will give you the id send via GET
die();
});
Simply follow the GET method , your form will send a GET request and it will come to this route here you can perform your desired function.
I finally figured out the problem, and the solution:
The problem is that the form should (optimally) be sent as POST (not GET), and therefore not changed from the default value provided by Blade. BUT then the route has to be registered correctly as POST, and that's what I wasn't doing before. So,
dashboard.blade.php:
{{ Form::model(null, array('route' => array('lookupsociety'))) }}
{{ Form::select('value', $societies) }} ...
Route:
Route::post('lookupsociety', array('as'=>'lookup society', 'uses'=>'SocietiesController#lookupsociety'));
SocietiesController#lookupsociety:
public function lookupsociety()
{
$id = Input::get('value'); ... // proceed to do whatever is needed with $id value passed from the select list
}
It works perfectly! The key was changing the method in the route to Route::post() instead of Route::get().
I knew it had to be simple -- I simply hadn't stumbled on the solution before :)

Categories