Apps route redirecting the wrong URL - laravel

------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');

Related

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

Laravel missing parameters to update form in controller

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...

Laravel 404 Not Found - But Route Exists

Hello im trying to get information about user on my view.
Here is my UserController
public function getUser(Request $request, $id)
{
$user = User::findOrFail($id);
return view('admin.user', ['user' -> $user]);
}
here is my web.php
Route::get('admin/user/{id}', "UsersController#getUser");
and my user view
#extends('admin.layouts.app')
#section('contents')
<h1>User {{ $user }} </h1>
#endsection
I am trying to display user information in this view, like name etc, but im recives 404
Not Found page. What im doing wrong. Im using Laravel 6
404 error may refer to a User not being found, since you have a findOrFail() query. It may have nothing to do with your routes.
Just double check with:
php artisan route:list
just to make sure the route is being registered correctly.
I think you firstly use any prefix for this route.For this it will give you an error.To check route list.
php artisan route:list
it will give you all route.
And Here you don't need (Request $request) because here you just need the id.it not the problem..i give you just this suggestion
public function getUser($id)
{
$user = User::findOrFail($id);
return view('admin.user', ['user'=> $user]);
}
why you use '-> ' you should use '=>'

Laravel 5.8 error trying to get the 'id' property of non-object

I'm developing an application with Laravel 5.8. In my application, I have a controller that handles backend articles, and it works. I want to display my user-side information in such a way that a user can click on a link and see the detail of an article. For that, I have created a new controller a with a new namespace for the function show my redirection of navigation in different page does not focus that it is en route or URL with Laravel 5.8. Below is the function.
namespace App\Http\Controllers\Cybernaut;
use App\History;
use App\Http\Controllers\Controller;
class HistoryController extends Controller
{
public function show($id)
{
$history = History::find($id);
return view('show_history', compact('history'));
}
}
At the level of the home page I wanted to have my links like these:
<li><a data-hover="history" href="{{route('history.show',$history→id)}}"><span>history</span></a></li>
Error
ErrorException (E_ERROR) Property [id] does not exist on this
collection instance. (View:
C:\laragon\www\venome\resources\views\layouts\partial\header.blade.php)
And here is the route used for the show function.
Route::group(['namespace'=>'cybernaut'], function (){
Route::get('/history/{slug}','HistoryController#show')->name('history.show');
});
Try after modifying the thing I have these at the route level now.
Route::get('/', 'FrontController#index')->name('index');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin/dashboard', 'DashboardController#index')->name('admin.dashboard');
Route::group([], function () {
Route::get('/history', 'HistoryController#index')->name('history.index');
Route::get('/history', 'HistoryController#create')->name('history.create');
Route::get('/history/edit', 'HistoryController#update')->name('history.update');
Route::get('/history', 'HistoryController#destroy')->name('history.destroy');
});
Route::group(['namespace' => 'cybernaut'], function () {
Route::get('/history/{history}', [
'as' => 'show',
'uses' => 'HistoryController#show'
]);
});
At the level of the homepage I wanted to put my link like those here now;
#foreach($history as $history)
<li><a data-hover="history" href="{{url('/history/'.$history->id)}}"><span>history</span></a></li>
#endforeach
I have this error now:
Trying to get property 'id' of non-object (View:
C:\laragon\www\venome\resources\views\layouts\partial\header.blade.php)
I want an internaut to be able to navigate between the pages.
You have a conflict of variables on your homepage.
#foreach($history as $history)
should be
#foreach($histories as $history)
where $histories is filled in in your FrontController.
$histories = History::all();
When actually getting your single history object, I agree with Sapnesh's answer that you best doublecheck whether or not the object actually exists.
The error occurs because find() returns NULL when a model is not found.
find($id) takes an id and returns a single model. If no matching model
exist, it returns null.
findOrFail($id) takes an id and returns a single model. If no matching
model exists, it throws an error.
In your show() method,
Change:
$history = History::find($id);
To:
$history = History::findOrFail($id);

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