I'm new in Laravel Here I am trying to post my input form in to a session but its not working I get this error without any message:
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
I found nothing, here I am sharing some of my code.
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use \App\Product;
class ShopController extends Controller
{
public function index()
{
$categories = Category::with('products')->get();
return view('shop.index', compact('categories'));
}
public function category($id)
{
$products = Category::find($id)->products;
return view('shop.1', compact('products'));
}
public function addToShoppingCart(Request $request)
{
$request->session()->put('cart', 'id');
$request->session()->put('cart', 'number');
$request->session()->flash('status', 'Product is toegevoegd!');
return redirect()->back();
}
}
My view:
#extends('layouts.app')
#section('content')
#if(Session::has('id', 'number'))
<div class="alert alert-success">
{{Session::get('id', 'number')}}
</div>
#endif
#foreach ($products as $product)
<ul>
<li>{{ $product->name }}</li>
<li>{{ $product->description }}</li>
<li>{{ $product->price }}</li>
<li>{{ $product->amount }}</li>
</ul>
<form method="post" action="{{url('categories\{id}')}}">
#csrf
<div class="col-md-4">
<label for="number">Aantal:</label>
<input type="number" name="number">
<label for="id">Id:</label>
<input type="text" id="id" name="id" value= {{$product->id}}>
<button type="submit" class="btn btn-success">Add product</button>
</div>
</form>
#endforeach
{{var_dump(Session::get('cart'))}}
#endsection
My routes:
Route::get('/shop', 'Shopcontroller#index')->name('shop');
Route::get('/categories/{id}', 'ShopController#category');
Route::get('/cart/{id}', 'ShopController#addToShoppingCart');
I hope someone can help me out with my problem to put the input in the session of laravel.
You are trying to "post" using a "get" route. You should change Route::get by Route::post
First of all, i suggest you use the route() method. There is nothing wrong with the url() method but i just using the route() method.
So let's solve your problem out!
1. Add names to your routes and set the ROUTE to POST instead of GET
Route::get('/shop', 'Shopcontroller#index')->name('shop');
Route::post('/categories/{id}', 'ShopController#category')->name('category');
Route::get('/cart/{id}', 'ShopController#addToShoppingCart')->name('cart.add');
2. Pass your route as an action to your form
action="{{route('category',['id' => 'your_category_id_here'])}}
3. Add use Session;
Your controller is missing the use Session; statement, add it on the top of the controller page so you can be able to use sessions.
Related
I'm start learning laravel and want to create sample login authorization system on my html template. I watched a tutorial and when i do everything that was in video i get error Undefined variable: erros.
I'm new and I don't know good PHP but i want to learn while creating a website I know a little.
my rout code is my route code :
this is route for my login code
Route::get ('/main', 'MainController#index');
Route::get ('/main/checklogin', 'MainController#checklogin');
Route::get ('/main/successlogin', 'MainController#successlogin');
Route::get ('/main/logout', 'MainController#logout');
1.my login code
<div class="login slide-up">
<div class="center">
<h2 class="form-title" id="login"><span>sign</span>in</h2>
#if (isset(Auth::user()->email))
<script>window.location="/main/successlogin"</script>
#endif
#if ($message = Session::get('error'))
<div class ="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">X</button>
<strong>{{$message}}</strong>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
#if(count($errors) >0 )
<div class="alert alert-danger">
<ul>
#foreach($erros->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
{{ csrf_field()}}
<div class="form-holder">
<input type="email" class="input" placeholder="email" />
<input type="password" class="input" placeholder="password" />
</div>
<button class="submit-btn">Sign in</button>
</div>
2.my successlogin code
<html>
<body>
#if (issets(auth::user()->email))
<p>gamarjoba {{Auth::user()->email}}}</p>
<a href="{{ url('/main/logout') }}" > logout </a>
else
<script>windows.location = "/main"; </script>
#endif
</body>
</html>
my main controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class MainController extends Controller
{
function index()
{
return view('front/login');
}
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:4'
]);
$user_data = array(
'email' => $request -> get('email'),
'password' => $request -> get('password')
);
if (Auth::attempt($user_data))
{
return redirect('main/successlogin');
}
else
{
return back()->with('error', 'wrong Login Details');
}
}
function successlogin()
{
return view('successlogin');
}
function logout()
{
Auth::logout();
return redirect('main');
}
}
Laravel made this easy:
Run php artisan make:auth
I'm learning Laravel and I got stuck trying to get data from a form.
I already am able to get data back with GET, but with POST I've been having a ton of trouble. Here's what I'm working with:
Form:
<form id="forms" method="POST" action="sugestoes" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
#php
if (isset($_POST["obs"])) {
echo "IN";
}
#endphp
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('sugestoes');
//
}
}
Route:
Route::post('sugestoes', 'PostController#store');
The intended behaviour that I'm trying to reach is for the post to be submitted, and then returning to the same page with an empty form. Later on I'll be sending the input data into a database, but for now I just want to get the post to work.
I guess I'm missing something really basic, but I've been following guides and looking online, I've done some progress but I'm really stuck here.
(some more info, this is Laravel 5.4, and I'm using XAMPP)
First, you need to call the model, use App/Your_model_name; then you have to save the data.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Suggest; //Suggest model, let's hope you have suggest table
class PostController extends Controller
{
public function store(Request $request)
{
$suggest = new Suggest; //model
$suggest->name = $request->obs; //name is DB name, obs is request name
$suggest->save(); //save the post to DB
return redirect()->back()->with('success', 'Saved successfully'); //return back with message
}
}
Then if you want to flash the message on the HTML page
#if(session('success'))
<div class="alert alert-warning alert-dismissible" id="error-alert">
<strong style="color: white;">{{session('success')}}</strong>
</div>
#endif
<form id="forms" method="POST" action="{{ route('sugestoes') }}" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
Remove the #php tag below the form, then in router.php
Route::post('/sugestoes', 'PostController#store')->name('sugestoes');
Then in Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('/sugestoes'); // you should have GET in Route.php
//
}
}
Add the following code in your action attribute on the form. It will capture the post URL. When you submit the form it will send the form data to the URL end-point.
action="{{ url('sugestoes')}}"
Then die and dump in your controller store function
public function store(Request $request)
{
dd($request->all());
}
I am making a todo list with validation using laravel 5.4.
When I click on the submit button, only the required validation is working but not the unique.
What am I doing wrong and how do I fix it so as to get it working as desired?
Below is my form (located at home.blade.php):
<div class="panel-body">
<form class="form form-control" action="/todo" method="post">
{{csrf_field()}}
<fieldset class="form-group">
<textarea class="form-control" name="textbox" id="textArea"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</form>
{{-- for dispaying the error --}}
#if (count($errors) >0)
{{-- expr --}}
#foreach ($errors->all() as $error)
<h3 class="text-danger">{{$error}}</h3>
#endforeach
#endif
</div>
Here, the content of my Todo controller (in my todocontroller.php file):
use Illuminate\Http\Request;
use App\todo;
public function store(Request $request)
{
$todo = new todo;
$todo->body = $request->textbox;
$this->validate($request,[
"body" => "required|unique:todos"
]);
$todo->save();
return redirect('/todo');
}
You should simply use the name of the field; you don't need to stress yourself.
Take a look at the snippet below:
<?php
namespace App\Http\Controllers;
use App\Todo;// following Laravel's standards, your model name should be Todo; not todo
use Illuminate\Http\Request;
class NameOfYourTodoController extends Controller
{
public function store(Request $request)
{
$todo = new Todo();
// use the name of the field directly (here, textbox)
$this->validate($request, [
'textbox' => 'required|unique:todos'
]);
// other code logics here.
}
}
I am new to Laravel and other PHP frameworks.
Try simple form and validating, like examples in https://laravel.com/docs/5.1/validation
routes.php
Route::get('/post/', 'PostController#create');
Route::post('/post/store', 'PostController#store');
create.blade.php
<html>
<head>
<title>Post form</title>
</head>
<body>
<h1>Create Post</h1>
<form action="/post/store" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name='title'>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
</body>
PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use View;
use Validator;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* #return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
$validator = Validator::make($request->all(), [
'title' => 'required|min:5'
]);
if ($validator->fails()) {
dd($validator->errors);
//return redirect('post')
//->withErrors($validator)
//->withInput();
}
}
}
When I post not valid data:
ErrorException in PostController.php line 37: Undefined property: Illuminate\Validation\Validator::$errors
Validator object nor have errors.
If enabled in controller
return redirect('post')->withErrors($validator)
->withInput();
and enabled in form
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Have error
ErrorException in c5df03aa6445eda15ddf9d4b3d08e7882dfe13e1.php line 1: Undefined variable: errors (View: /www/alexey-laravel-1/resources/views/post/create.blade.php)
This error in default get request to form and after redirect from validator.
For $errors to be available in the view, the related routes must be within the web middleware:
Route::group(['middleware' => ['web']], function () {
Route::get('/post/', 'PostController#create');
Route::post('/post/store', 'PostController#store');
});
I'm trying to add validation to my resource controller using the laravel's validation (http://laravel.com/docs/5.1/validation) but I get this error:
ErrorException in ValidatesRequests.php line 30:
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an
instance of Illuminate\Http\Request,
instance of Illuminate\Support\Facades\Request given,
called in
/Users/lextoc/Documents/Sites/partyrecycler/app/
Http/Controllers/MarkerController.php on line 30 and defined
This is the controller:
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Marker;
class MarkerController extends Controller
{
...
public function create()
{
return view('markers.create');
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'x' => 'required',
'y' => 'required',
]);
$marker=Request::all();
Marker::create($marker);
return redirect('markers');
}
...
}
And the view:
<h1>Create marker</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
{!! Form::open(array('route' => 'markers.store')) !!}
{!! csrf_field() !!}
<div>
Name
<input type="text" name="name">
</div>
<div>
x
<input type="text" name="x">
</div>
<div>
y
<input type="text" name="y">
</div>
<div>
<button type="submit">Create</button>
</div>
{!! Form::close() !!}
I don't know why it's using the wrong Request class, and why are there two being used in the controller?
The error is due to your include headers:
Try
use Illuminate\Http\Request;
Instead of
use Request;
Example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Marker;