Laravel missing parameters to update form in controller - laravel

So I have a little project, in it, there's the possibility to upload banners images to be shown on the main page. All the stuff related to the DB are already created and the option to create a banner is working, it creates the banner and then stores the image on the DB for use later. Now I'm trying to work on an edit function so I can change the description under the bannners. I have an Edit route in my controller which returns a view where I edit said banner then it calls the update function on the controller. But no matter what I put here, I'm always getting the Missing Required Parameters error once I try to Save the edit and open my controller through the Update function. Here's the code as it is now:
The route definition:
Route::resource('banner', 'BannerController');
The edit function on my controller:
public function edit($id)
{
return view('admin/edit-banners',['id'=>$id]);
}
The update function has not been implemented because I always start with a dd() function to check if everything is working fine:
public function update(Request $request, $id)
{
dd($request);
}
And here's the form line in my edit view that is trying to call the update route:
<form class="card-box" action="{{ route('banner.update',[$banner]) }}">
I also added this at the beginning of the view to store the data from the DB into a variable:
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
The $banner variable contains all the information on the banner being edited, and I can get the new description at the controller with the $request variable, so I honestly don't know what should I put here as parameters, any ideas?

The $banner variable is not a Model instance, it is a Collection.
Adjust your controller to pass this to the view instead of dong the query in the view:
public function edit($id)
{
$banner = Banner::findOrFail($id);
return view('admin.edit-banners', ['banner' => $banner]);
}
You could also use Route Model Binding here instead of doing the query yourself.
Remove that #php block from your view.
The form should be adjusted to use method POST and spoof the method PUT or PATCH (as the update route is a PUT or PATCH route) and you should adjust the call to route:
<form class="card-box" action="{{ route('banner.update', ['banner' => $banner]) }}" method="POST">
#method('PUT')

If you include $id in your function declaration then when you call the route helper it expects you to give it an id parameter. Try with
<form class="card-box" action="{{ route('banner.update',['id' => $id]) }}">
You should be able to retrieve the form data just fine form the $request variable. More info here.

The code below should be the error source. $banner variable then is an array but the update function accept object or id.
#php
use\App\Banner;
$banner = Banner::where('id','=',$id)->get();
#endphp
You should try to replay this code by this one...
#php
use\App\Banner;
$banner = Banner::find($id);
//you should put a dd here to view the contain of $banner if you like
#endphp
Hop it help...

Related

retrieve database values in register page in laravel

I have registration auth in laravel project and i need some existing datas should show up on the registration form , please guide me up..
http://165.232.187.63/register
This is my register page and i need to fetch existing database values in the registration form. for example
<select>
#foreach($users as $items)
<option>{{ $items->id }}</option>
#endforeach
</select>
How to customize this...
I have tried adding in web.php file
Route::get('/register','App\Http\Controllers\Auth\UserController#index');
And in my UserController.php
public function index()
{
$users = User::all();
return view('auth.register')
->with('users', $users);
}
But can't use both post and get for register auth
You need to use separate endpoints for this task
one to load the view
Route::get('/register','App\Http\Controllers\Auth\UserController#index');
and the other to do the actual registration
Route::post('/register','App\Http\Controllers\Auth\UserController#register');
of course in the UserController, you will have a register method that handles the actual registration process

How to destroy a record using a form in Laravel and display status?

I'm using Laravel and I am currently implementing the 'destroy' method in a resource controller as part of CRUD. The method should delete the specified record in my database.
The method is called by my blade.php file, which uses a form with the DELETE method and route('my-resources.destroy', $my-resource->id). I want the controller to return a string such as 'Deleted successfully!' so that I can display that to the client.
Here is my code:
In views/book/edit.blade.php:
<form method="DELETE" action="{{ route('books.destroy', $book->id) }}">
<div class="form-item center">
<button type="submit" class="btn-danger">Delete</button>
</div>
</form>
and in BookController.php:
public function destroy($id)
{
$book = Book::find($id);
$book->delete();
return redirect()->away('https://www.google.com');
}
I put a redirect to google.com just to see if the redirect works, but it doesn't. When I click the 'Delete' button, the url changes from http://127.0.0.1:8000/books/1/edit to http://127.0.0.1:8000/books/1? with that question mark at the end. What am I doing wrong?
I have another question: if I want to return the status, should I use something like
Route::get('/', function () {
return 'Deleted successfully';
});
or
$request->session()->flash('status', 'Task was successful!');
/** and some random return statement **/
Thanks!
Forms do not support the DELETE method so you need to use the Laravel #method helper to tell Laravel you want to use the DELETE verb. Additionally, you need to include the csrf token that Laravel expects are part of preventing cross-site request forgeries.
<form action="{{ route('books.destroy', $book->id) }}" method="POST">
#csrf
#method("DELETE")
... // Button/link for submit this form
</form>
You may need to define your route so that it accepts a DELETE request, unless you have defined a resourceful route:
Route::delete('/books/{id}', 'BookController#destroy')
->name('books.destroy'); // Laravel 7
Route::delete('/books/{id}', [\App\Http\Controllers\BookController::class, 'destroy'])
->name('books.destroy'); // Laravel 8
If you're using resourceful routes, they will be made available for you already:
Route::resource('/books', 'BookController'); // Laravel 7
Route::resource('/books', \App\Controllers\Http\BookController::class); // Laravel 8
For your destroy method, set a flash message to be sent back:
public function destroy(Book $id)
{
$id->delete();
return redirect('/')->with('success', 'Book deleted');
}
Then flash the message in your view:
#if (session('success'))
<p>{{ session('success') }}</p>
#endif

Apps route redirecting the wrong URL

------Platform Laravel 7x. --------
I am stuck in a simple problem. I can't find the error. While I am updating a form, it redirects to a wrong URL which I don't want and data doesn't update.
Form action url:
method="POST" action="{{'city/update/'. $editCity->id}}"
form image
Route:
Route::post('city/update/{id}','Admin\CityController#update');
web route
Function from controller:
public function update(Request $request, $id)
{
$editCity=City::find($id);
$editCity->city_name=$request->city_name;
$editCity->save();
return redirect()->back();
}
function from controller
When I click on update it goes to this URL and shows 404 error which I don't want:
public/panel/city/edit/city/update/33
Help me to find out the problem where is the mistake I have done. I want to make it updated when I click on the update button and return back.
Use name route instead.
So your code will look like :
blade.php
method="POST" action="{{ route('city.update', $editCity->id) }}"
web.php
Route::post('city/update/{id}','Admin\CityController#update')->name('city.update');
In case your CityController is a resource controller, this what you should try:
Route: web.php
Route::resource('city', 'Admin\CityController');
Form: HTML
<form action="{{route('city.update',$editCity->id)}}" method="post">
Controller: CityController.php
public function update(Request $request, $id)
{
$editCity=City::find($id);
$editCity->city_name=$request->city_name;
$editCity->save();
return back()->with('success','city added successfully!');
}
I hope it helps !
While creating your controller did you run such command ?:
php artisan make:controller Admin\CityController --resource
You should create the controller as a resource controller, then declare it
in your routes like this:
Route::resource('city', 'Admin\CityController');
Ps: Make sure to remove in web.php, your old route:
Route::post('city/update/{id}','Admin\CityController#update')->name('city.update');

Route model binding not working on Laravel

I have been trying to solve this issue since two days but no luck. I do have a update method on my ArticleController that is responsible to update the articles on my database:
public function update(Article $articles, ArticleRequest $request){
$article = Article::findOrFail($articles);
$article->update($request->all());
return redirect('articles');
}
Here is my blade file to show those results:
#extends('app')
#section ('content')
<div class="container">
<h1>Edit: {{$article->title}}</h1>
{!!Form::model($article,['method'=>'PATCH', 'action'=>['ArticleController#update', $article->id] ])!!}
#include('pages.partials', ['submitButtonText' => 'Edit Article'])
{!!Form::close()!!}
#include('errors.error')
</div>
#endsection
I get error Article var doesnt exists.
When you set up route-model binding, behind the scenes Laravel retrieves the appropriate model instance for you and passes it into your controller method. In your example, the Article $articles argument represents an instance of the Article model - not just the id. Therefore, the following line is both unnecessary (since you already have the appropriate model instance), and incorrect (since findOrFail expects an integer to be passed to it - not a model instance):
$article = Article::findOrFail($articles);
I would change your controller method to be:
public function update(Article $articles, ArticleRequest $request)
{
$articles->update($request->all());
return redirect('articles');
}
If you still have trouble with that, "die and dump" your $articles variable to ensure you have route-model binding set up correctly.

Passing parameter from route to controller in laravel

I am trying to pass a variable from route to controller. But not able to succeed.
my route entry is as below
Route::get('/Register', 'NewRegister#CheckCand');
now in the controller file I want to get one parameter. My controller function is as below
public function CheckCand()
{
echo $ID;
}
Now how do I pass a variable ID from route to controller. But i don't want to pass it in the URL and also in get function i dont want to change '/Register'.
Route::get('/Register', 'NewRegister#CheckCand');
Means it will be like a Hidden parameter passed from route to controller.
Might be question is confusing but i don't know how to explain better.
You can retrieve the parameters by Request so in your function request the parameters as you named when you passed them
public function CheckCand(){
$request = Request::all();
$ID = $request->ID ;
// Or
$ID = $request['ID'];
}
Pass as request parameter and retrieve it in the controller using request. Something like below.
jQuery
$.get('/register', {ID :'123'}, function(data) {});
or
Javascript
...
<form id="register-form" action="{{ url('register') }}" method="GET" style="display: none;"><input type="hidden" name="ID" value="..."/></form>
Controller
public function CheckCand(Request $request) {
$request->ID;
}

Resources