Redirect error laravel - laravel

Hello i am using createProduct page for my create form. And after i created a product i want to redirect to the same page with parameters. Can you help me with the following error please ?
web.php
Route::get('/admin/products/create','productsController#createProduct');
Route::post('/admin/products/creating','productsController#creatingProduct');
creating function
public function creatingProduct(){
$product = new Product();
$product->name = Input::get('name');
$product->description = Input::get('description');
$product->price = Input::get('price');
$categories = Category::all();
try {
$product->save();
$pageMessage = prepareMessage("alert-success","Yahoooo!!","Eklendiii");
} catch ( \Illuminate\Database\QueryException $e) {
$pageMessage = prepareMessage("alert-danger","Üzgünüz!!","Ürününüz eklenemedi");
}
// return view('admin.createProduct',compact('categories','pageMessage'));
return Redirect::route('/admin/products/create')->with( 'pageMessage', $pageMessage );
}
create function
public function createProduct(){
$categories = Category::all();
return view('admin.createProduct',compact('categories'));
}
createProduct.bladde.php
#if(isset($pageMessage))
{!!$pageMessage!!}
#endif
<form class="well form-horizontal" action=" {{url('admin/products/creating')}}" method="POST" id="contact_form">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<!--{{ Form::open(['url' => '/admin/products/create', 'files' => true]) }}-->
<div class="form-group">
<label class="col-md-4 control-label">Ürün İsmi</label>
<div class="col-md-8 inputGroupContainer">
ERROR
InvalidArgumentException in UrlGenerator.php line 314:
Route [/admin/products/create] not defined.

You're passing a URL into Redirect::route() which expects the name of a route instead.
return redirect('/admin/products/create')->with( 'pageMessage', $pageMessage );
If you're using an older version of Laravel I believe it would be
return Redirect::to('/admin/products/create')->with( 'pageMessage', $pageMessage );
You can set up a named route and use that also, it's quite simple:
Route::post( '/admin/products/creating', [
'uses' => 'productsController#creatingProduct',
'as' => 'products.create'
]);
The benefits are that you can reference the route name throughout your application and if you decide to change the format of the URL you only have to do it in the one spot.

You should use route name instead of url if you're using route():
return redirect()->route('products.create');
So you can name your route:
Route::get('/admin/products/create', ['as' => 'products.create', 'uses' => 'productsController#createProduct']);
As alternative, you can use url like this:
return redirect('/admin/products/create');

You defined Redirect::route() which is not define you inside your route file.
It should be like below:
return Redirect::to('/admin/products/create')->with( 'pageMessage', $pageMessage );

Related

laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD

hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
route:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
view:
<form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data">
<div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10">
#if($product->product_status == 1)
<!-- Button -->
<button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Add to Cart
</button>
#else Out Of Stock #endif
</div>
</form>
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
First of all your form method in the view is POST but you don't have a post route.
Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form.
Here's the form action:
action="{{ route('addToCart', $product->id) }}"
And if you want to use link, you can do something like this:
.....
Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post
Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }}
<form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Getting errors while submitting the form in laravel 5.5

I am getting either of 2 errors one after the other.
While submitting the form either I get the error below
The page has expired due to inactivity. Please refresh and try again.
Or this error
InvalidArgumentException
Route [register/user/image] not defined.
I have cross checked everything unable to find out the real cause.
Routes/web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::prefix('manage')->middleware('role:superadministrator|administrator|editor|member')->group(function() {
Route::get('/', 'ManageController#index');
Route::get('/carezone', 'ManageController#carezone')->middleware('role:superadministrator|administrator')->name('manage.dashboard');
Route::get('/dashboard', 'ManageController#dashboard')->name('manage.dashboard');
});
Route::middleware('role:superadministrator|administrator|editor|member|subscriber')->group(function() {
Route::get('register/user/details', 'RegisterUserController#showUserDetailsForm')->name('register.user.details');
Route::post('register/user/details', 'RegisterUserController#postUserDetailsForm')->name('register.user.details');
Route::get('/api/username/unique', 'RegisterUserController#apiCheckUniqueUserName')->name('api.username.unique');
Route::get('register/user/image', 'RegisterUserController#showUserImageForm')->name('register.user.image');
Route::post('register/user/image', 'RegisterUserController#postUserImageForm')->name('register.user.image');
});
Route::get('/email/unique', 'RegisterUserController#checkUniqueEmail')->name('email.unique');
Route::get('/get/city', 'RegisterUserController#ajaxGetCity')->name('get.city');
Route::get('/registration', 'RegisterUserController#showRegistrationForm')->name('registration');
Route::get('/home', 'HomeController#index')->name('home');
RegisterUserController.php
/*function to redirect user to user details page after register page*/
public function showUserDetailsForm() {
$states = State::all();
return view('pages.registration.registerUserDetails', ['states'=> $states]);
}
/*function to post and save data to the database*/
public function postUserDetailsForm(Request $request) {
$validatedData = $request->validate([
'username' => 'required|alpha_num|min:6|max:20|unique:details,username',
'dob' => 'required|date',
'gender' => 'required|string',
'state' => 'required|numeric',//validation rule for max min values
'city' => 'required|numeric',//validation rule for max min values
]);
$post = new Detail;
$post->user_id = Auth::user()->id;
$post->username = $request->username;
$post->dob = $request->dob;
$post->gender = $request->gender;
$post->state_id = $request->state;
$post->city_id = $request->city;
$post->save();
return redirect()->route('register/user/image');
}
Small Portion Of my form
<form id="registerUserDetails" class="form-horizontal clearfix" method="POST" action="{{ route('register.user.details') }}" role="form" novalidate>
{{ csrf_field() }}
.
.
.
.
<button type="submit" class="tabButton">Next</button>
</form>
<script>Javascript Validation here</script>
To solve the second error you must fix your route name on your controller method (and everywhere):
Actual:
return redirect()->route('register/user/image');
Correct:
return redirect()->route('register.user.image');
For solving the first error add the csrf field {{ csrf_field() }} to form
And for the second one, you route's name is register.user.image
so set the form's action like this
<form action=" {{ route('register.user.image') }} ">

Laravel insert into mysql db from a controller function

I am trying to submit records into a mysql table with many fields by using a Laravel .blade.php view ( php form)
I made some trials but I get
FatalErrorException in loginController.php line 54: Class 'App\Http\Controllers\Input' not found.
Mysql
create table users(id int primary key auto_increment,username varchar(20),password varchar(20),createDate timestamp );
My controller function
public function formSubmit()
{
if (Input::post())
{
$username = Input::get('username');
$password = Input::get('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return View::make('view2')->with(array('username' =>$username, 'password' => $password));
}
}
view1.blade.php form
<form action="{{url('/view2') }}" method="POST">
{{ csrf_field() }}
<input type ="hidden" name="">
User name: <input type ="text" name="username"> <br/>
Password <input type="password" name="password"> <br/>
<input type="submit" name="formSubmit" value="formSubmit">
</form>
Route
Route::get('/view1', 'loginController#formSubmit');
Add use Input; to the top of your class right after namespace clause.
Or use full namespace:
$username = \Input::get('username');
$password = \Input::get('password');
Or you just could use only() method to get an array from request:
DB::table('users')->insert(request()->only('username', password));
Also, never save raw passwords. Use bcrypt() to encrypt passwords.
Since you're using Laravel 5, use the Request Facade and acces input this way:
Request::input()
instead of using Input();
https://laravel.com/docs/5.0/requests
And, just in case, include it at the top of the Controller with
use Illuminate\Support\Facades\Request;
Referring to Amarnasan answer I used request and include use Illuminate\Http\Request; at the top of my controller.
So I changed my controller method to
public function formSubmit(Request $req)
{
$username =$req->input('username');
$password =$req->input('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return view ('view2')->with(array('username' =>$username, 'password' => $password));
}
}
and I changed my routes according to Shubham pokhriyal commit to:
Route::post('/view2', 'loginController#formSubmit');
Route::get('view1',function()
{
return view('view1');
}
);
and it works fine.

Laravel Editing post doesn't work

There are routes
Route::get('posts', 'PostsController#index');
Route::get('posts/create', 'PostsController#create');
Route::get('posts/{id}', 'PostsController#show')->name('posts.show');
Route::get('get-random-post', 'PostsController#getRandomPost');
Route::post('posts', 'PostsController#store');
Route::post('publish', 'PostsController#publish');
Route::post('unpublish', 'PostsController#unpublish');
Route::post('delete', 'PostsController#delete');
Route::post('restore', 'PostsController#restore');
Route::post('change-rating', 'PostsController#changeRating');
Route::get('dashboard/posts/{id}/edit', 'PostsController#edit');
Route::put('dashboard/posts/{id}', 'PostsController#update');
Route::get('dashboard', 'DashboardController#index');
Route::get('dashboard/posts/{id}', 'DashboardController#show')->name('dashboard.show');
Route::get('dashboard/published', 'DashboardController#published');
Route::get('dashboard/deleted', 'DashboardController#deleted');
methods in PostsController
public function edit($id)
{
$post = Post::findOrFail($id);
return view('dashboard.edit', compact('post'));
}
public function update($id, PostRequest $request)
{
$post = Post::findOrFail($id);
$post->update($request->all());
return redirect()->route('dashboard.show', ["id" => $post->id]);
}
but when I change post and click submit button, I get an error
MethodNotAllowedHttpException in RouteCollection.php line 233:
What's wrong? How to fix it?
upd
opening of the form from the view
{!! Form::model($post, ['method'=> 'PATCH', 'action' => ['PostsController#update', $post->id], 'id' => 'edit-post']) !!}
and as result I get
<form method="POST" action="http://mytestsite/dashboard/posts?6" accept-charset="UTF-8" id="edit-post"><input name="_method" type="hidden" value="PATCH"><input name="_token" type="hidden" value="aiDh4YNQfLwB20KknKb0R9LpDFNmArhka0X3kIrb">
but why this action http://mytestsite/dashboard/posts?6 ???
Try to use patch instead of put in your route for updating.
Just a small tip you can save energy and a bit of time by declaring the Model in your parameters like this:
public function update(Post $id, PostRequest $request)
and get rid of this
$post = Post::findOrFail($id);
EDIT
You can use url in your form instead of action :
'url'=> '/mytestsite/dashboard/posts/{{$post->id}}'
Based on the error message, the most probable reason is the mismatch between action and route. Maybe route requires POST method, but the action is GET. Check it.
Try to send post id in hidden input, don't use smt like that 'action' => ['PostsController#update', $post->id]
It contribute to result action url.

laravel 5.3 old input values always empty

see docs here about old input
Route::post('/search/all/', function (Request $request) {
//...
$products = $query->paginate(15);
$data = ['products' => $products,
'oldinput' => $request->all()];
return view('inventory.search_products', $data);
});
in the view:
this works:
<input type="text" id="search_all" name="search_all" value="{{ $oldinput['search_all'] }}">
this is always empty:
<input type="text" id="search_all" name="search_all" value="{{ old('search_all') }}">
Just call flush in your controller then you can use old() helper function in your blade.
public function YourController(Request $request){
$request->flash();
return view('yourblade');
}
In blade file:-
<input id="lng" name="lng" value="{{old('lng')}}" type="hidden">
docs says you should flash() then call old() method.
flashing stores the previous request in the session. so it makes sense that old(search_all) doesn't work
I will suggest the following solution:
return view('inventory.search_products', $data)->withInput(\Input::all());
And in blade you can call as well \Input::old('search_all');.

Resources