Having creating a code for Excel upload I am getting the below mentioned error...
MethodNotAllowedHttpException in RouteCollection.php
The codes written in VIEW is
views/items/items
#extends('layouts.master')
#section('content')
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-6">
<div class="row">
<form action="{{route('items.import')}}" method="POST" enctype="multipart/form-data">
<div class="col-md-6">
{{csrf_field()}}
<input type="file" name="imported-file"/>
</div>
<div class="col-md-6">
<button class="btn btn-primary" type="submit">Import</button>
</div>
</form>
</div>
</div>
<div class="col-md-2">
<!-- <button class="btn btn-success">Export</button> -->
</div>
</div>
#endsection
The codes written in route.php is...
Route::get('/items', 'ItemController#index');
Route::post('/items/import',[ 'as' => 'items.import', 'uses' => 'ItemController#import']);
ItemController.ASPX
public function index()
{
return view('items.items');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function import(Request $request)
{
if($request->file('imported-file'))
{
$path = $request->file('imported-file')->getRealPath();
$data = Excel::load($path, function($reader) {
})->get();
if(!empty($data) && $data->count())
{
$data = $data->toArray();
for($i=0;$i<count($data);$i++)
{
$dataImported[] = $data[$i];
}
}
Inventory::insert($dataImported);
}
return back();
}
Can anyone please help me what am missing in my coding that outputs the error...
Try this code instead of yours:
Route::post('/items/import',[ 'as' => 'items/import', 'uses' => 'ItemController#import']);
The trick is - the route needs to be named.
To avoid future confusion, it's better to name it as "items.import", so later you can identify for yourself that this is a "name" of a route.
So the final code would be:
Route::post('/items/import',[ 'as' => 'items.import', 'uses' => 'ItemController#import']);
and in blade template u call it like that:
<form action="{{route('items.import')}}"...
Related
I want to add data in database in Laravel, but I get error.
This is my Error:
ArgumentCountError
Too few arguments to function App\Http\Requests\Admin\Categories\StoreRequest::Illuminate\Foundation\Providers{closure}(), 0 passed in E:\xampp\htdocs\cylinders\cylinders\vendor\laravel\framework\src\Illuminate\Macroable\Traits\Macroable.php on line 124 and exactly 1 expected
Here is my Route:
Route::post('', [CategoriesController::class, 'store'])->name('admin.categories.store');
my page:
<form action="{{ route('admin.categories.store') }}" method="post">
#csrf
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Slug</label>
<input type="text" class="form-control" name="slug">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title">
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary float-left">Save</button>
</div>
</form>
my Contoller:
public function store(StoreRequest $request)
{
$validatedData = $request->validate();
$createdCategory = Category::create([
'title' => $validatedData['title'],
'slug' => $validatedData['slug'],
]);
if(!$createdCategory){
return back()->with('failed', 'Failed to Create Category.');
}
return back()->with('success', 'Success to Create Category.');
}
my Request:
<?php
namespace App\Http\Requests\Admin\Categories;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|min:3|max:128|unique:categories,title',
'slug' => 'required|min:3|max:128|unique:categories,slug',
];
}
}
little bit stuck with redirecting to other page after successful login for quite a long time. I believe that my understanding about sanctum auth is a bottleneck for this issue( Or maybe I am wrong ). However, after reading the docs still couldn't find the answer to my issue. Situation: I have declared few public routes and one private. I have created a user in my database and whenever I try successfully to log in it does not redirect to other page, and my credentials are 110% correct, but anyway after submit it only displays:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/dashboard] not defined.
However, I have that route, it's protected but after sign in I assign it. Maybe I am doing in a wrong way?
welcome.blade:
#section('content')
<div class="container-fluid">
<div class="container">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<form action="{{action('App\Http\Controllers\AuthController#login')}}" method="POST">
#csrf
<input type="text" class="form-control" placeholder="Email address" name="username" required>
<input type="password" class="form-control" placeholder="Password" name="password" required>
<div class="login-btn">
<button type="submit" class="btn btn-success">Sign in</button>
</div>
</form>
</div>
</div>
</div>
#endsection
AuthController:
public function login(Request $request)
{
$fields = $request->validate([
'username' => 'required',
'password' => 'required',
]);
$user = User::where('username', $fields['username'])->first();
if (!$user || !Hash::check($fields['password'], $user->password)) {
return Redirect::back()->withInput()->withErrors('Incorrect username or password');
} else {
$token = $user->createToken($request->username);
return redirect()->route('/dashboard')->with('token', $token);
}
}
web.php :
// Private routing
Route::group(['middleware' => ['auth:sanctum']], function () {
// Agents dashboard
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');
});
// Public routing
Route::get('/', function () {
return view('welcome');
});
Route::post('/login', [AuthController::class, 'login'])->name('login');
Dashboard -> main:
#extends('layouts.app')
#section('content')
<h1>Private</h1>
#endsection
change ->route('/dashboard') to ->route('dashboard'). This value references the name value on a route. eg:
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');
I have a contact form that when submitted, is successfully going to the DB. The issue is, when I check for validation on my webpage, the errors appear properly using Larvael $error validation, the problem is that my webpage always redirects back to home when errors show up instead of the page remaining still and showing the errors. I have to keep scrolling down to where my contact form is to see the errors; this will be annoying for my future users. How do I get the page to remain where it is if there are errors? NOTE: My page redirects correctly when the form is valid and submitted, this is not an issue. NOTE-2: I have created a single page webpage that the nav-links take you to, there are no redirects. Instead, it is one HTML page.
Web.php
Route::get('/', 'HomeController#index')->name('home');
Route::post('/contact/submit', 'MessagesController#submit');
MessagesController.php
namespace App\Http\Controllers;
use App\Message;
use Illuminate\Http\Request;
class MessagesController extends Controller
{
public function submit(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
Message::create($validatedData);
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
}
contact.blade.php
{{--CONTACT FORM--}}
<section id="contact">
<div class="container-fluid padding">
<div class="row text-center padding">
<div class="col-12">
<h2 class="lead display-3">Contact Us</h2>
<hr class="my-4">
<form action="/contact/submit" method="POST">
#csrf
<div class="field">
<label for="name" class="label">Name</label>
<div class="control">
<input type="text" class="input {{$errors->has('name') ? 'is-danger' : 'is-success'}}"
name="name" placeholder="Project Title" value="{{old('name')}}">
</div>
</div>
<div class="field">
<label for="name" class="label">Email</label>
<div class="control">
<input type="text" class="input {{$errors->has('email') ? 'is-danger' : 'is-success'}}"
name="email" placeholder="Project Title" value="{{old('email')}}">
</div>
</div>
<div class="field">
<label for="name" class="label">Phone Number</label>
<div class="control">
<input type="text"
class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
name="phonenumber" placeholder="Project Title" value="{{old('phonenumber')}}">
</div>
</div>
<div class="field">
<label for="message" class="label">Message</label>
<div class="control">
<textarea name="message"
class="textarea {{$errors->has('message') ? 'is-danger' : 'is-success'}}"
placeholder="Project description">{{old('message')}}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
<!--Errors variable used from form validation -->
#if($errors->any())
<div class="notification is-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</form>
</div>
</div>
</div>
</section>
You need to create a manual validator so that you have control over the redirect if the validation fails (which I assume is what you are having issues with).
public function submit(Request $request)
{
$validator = Validator::make($request->all(),[
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
if ($validator->fails()) {
return redirect(url()->previous() .'#contact')
->withErrors($validator)
->withInput();
}
Message::create($request->all());
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
First, move the errors to the top of the form so you can see them.
<form action="/contact/submit" method="POST">
#csrf
#if($errors->any())
<div class="notification is-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
A better way of handling validation is to separate it using a form request.
php artisan make:request SendMessageRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendMessageRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
];
}
}
If validation fails, a redirect response will be automatically generated to send the user back to their previous location.
Now update your controller.
use App\Http\Requests\SendMessageRequest;
use App\Message;
class MessagesController extends Controller
{
public function submit(SendMessageRequest $request)
{
Message::create($request->validated());
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
}
You can leave the validation in your controller using the Validator and back() redirection, but the first is the better way.
public function submit(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
if ($validator->fails()) {
return back()->withInput()->withErrors($validator);
}
Message::create($request->all());
return redirect('/')->with('success,' 'Your message has been
successfully sent. We will reach out to you soon');
}
I am creating a website for a blog. I have added a category page quickly updated, but not returned to the index: category.php,CategoriesController.php. I'm using Laravel v5.5 and OpenServer.
Category.php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['title', 'slug',];
public function user()
{
return $this->belongsToMany(
User::class,
'id_idcat',
'gid',
'idcat'
);
}
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
CategoriesController.php
namespace App\Http\Controllers\Admin;
use App\Category;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use View;
class CategoriesController extends Controller
{
public function index()
{
$categories = Category::all();
return view('admin.categories.index', ['categories' => $categories]);
}
public function create()
{
return view('admin.categories.create');
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required' //обязательно
]);
Category::create($request->all());
return redirect()->route('admin.categories.index');
}
}
create.blade.php
{!! Form::open(['route' => 'categories.store']) !!}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" name="cat">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}
I can not find a mistake. I did similar tasks several times.
Your Data isn't validating as there is no input named title because it's named cat, so your validator is redirecting you back with errors, but your blade isn't showing errors so you don't see them.
Change Name of the field in your create view and add errors as below:
Edit: also add CSRF to form
create.blade.php
#if ($errors->any())
<div class="alert alert-danger" role="alert">
#foreach ($errors->all() as $input_error)
{{ $input_error }}
#endforeach
</div>
#endif
{!! Form::open(['route' => 'categories.store']) !!}
{{ csrf_field() }}
<div class="box-header with-border">
<h3 class="box-title">Добавляем категорию</h3>
</div>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Название</label>
<input type="text" class="form-control" idcat="exampleInputEmail1" placeholder="" name="title">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-default">Назад</button>
<button class="btn btn-success pull-right">Добавить</button>
</div>
<!-- /.box-footer-->
{!! Form::close() !!}
I am building an application using Laravel 5.2. I'm trying to create an Edit modal using jquery. However I am getting a 500 internal server error, every time I try to update a record in the database. On further investigation using Firebug I get the error:
"Creating default object from empty value"...
These are the relevant code blocks.
Route.php - The edit route is what I'm trying to access from my modal
<?php
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/signup', [
'uses' => 'UserController#postSignup',
'as' => 'signup']);
Route::post('/signin', [
'uses' => 'UserController#postSignin',
'as' => 'signin']);
Route::get('/logout', [
'uses' => 'UserController#getLogout',
'as' => 'logout']);
Route::get('/dashboard', [
'uses' => 'PostController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Route::post('/createpost', [
'uses' => 'PostController#CreatePost',
'as' => 'createpost',
'middleware' => 'auth']);
Route::get('/delete-post/{post_id}', [
'uses' => 'PostController#getDeletePost',
'as' => 'post.delete',
'middleware' => 'auth']);
Route::post('/edit', [
'uses' => 'PostController#getEditPost',
'as' => 'edit'
]);
});
PostController.php
public function getEditPost(Request $request)
{
$this->validate($request, [
'body' => 'required'
]);
$post = Post::find($request['postid']);
$post->body = $request['body'];
$post->update();
return response()->json(['new_body' => $post->body], 200);
}
The Javascript file with the click event, app.js. I am printing a message to the console upon successful update of the database
var postId = 0;
$('.post').find('.interaction').find('.edit').on('click', function (event) {
event.preventDefault();
var postBody = event.target.parentNode.parentNode.childNodes[1].textContent;
postId = event.target.parentNode.dataset['postid'];
$('#post-body').val(postBody);
$('#edit-modal').modal();
});
$('#modal-save').on('click', function () {
$.ajax({
method: 'POST',
url: url,
data: {body: $('#post-body').val(), postId: postId, _token: token}
}).done(function (msg) {
console.log(JSON.stringify(msg));
});
});
This is my view page
dashboard.blade.php
#extends('layouts.master')
#section('content')
#include('includes.message-block')
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>What do you have to say?</h3></header>
<form action="{{ route('createpost') }}" method="post">
<div class="form-group">
<textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your Post"></textarea>
</div>
<button type="submit" class="btn btn-primary">Create Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
</div>
</section>
<section class="row posts">
<div class="col-md-6 col-md-offset-3">
<header><h3>What other people say...</h3></header>
#foreach($posts as $post)
<article class="post" data-postid="{{ $post->id }}">
<p>{{ $post->body }}</p>
<div class="info">
Posted by {{ $post->user->first_name }} on {{ $post->created_at }}
</div>
<div class="interaction">
Like |
Dislike
#if(Auth::user() == $post->user)
|
Edit |
Delete
#endif
</div>
</article>
#endforeach
</div>
</section>
<div class="modal fade" tabindex="-1" role="dialog" id="edit-modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Edit Post</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="post-body">Edit the Post</label>
<textarea class="form-control" name="post-body" id="post-body" rows="5"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script>
var token = '{{ Session::token() }}';
var url = '{{ route('edit') }}';
</script>
#endsection
Please can anyone help me to see what I'm missing here? Thanks
It looks like you get null on $post = Post::find($request['postid']);.
Do some checks before trying to update the model.
You can use ::findOrFail() or check if !is_null($post).
Also you should use $request->input('postid').