Laravel simple validation doens't work on resource method - php

Basically i have this form on userblog/create.blade.php
<form action="{{route('userblog.store')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label style="font-family: SansBold">تیتر وبلاگ:</label>
<input type="text" name="blog_title"
class="form-control">
</div>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">
Save
<i class="icon-arrow-left13 position-right"></i></button>
</div>
<br/>
</form>
with this route on web.php
Route::group(['middleware' => ['auth:web'], 'prefix' => 'page'], function () {
$this->resource('userBlog', 'UserBlogController');
});
now I'm trying to check posted form on Controller with this code and store them on database:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'blog_title' => 'required|min:10',
'blog_content' => 'required|min:10',
]);
if ($validator->failed()) {
return back();
} else {
dd('store on database');
}
}
in this my code i get
Route [userblog.store] not defined
error and when i change form action to /page/userBlog i get [] on $validator

The routes name should be like resource name. Replace your resource name or Route name like:
$this->resource('userblog', 'UserBlogController');
or
.. action="{{route('userBlog.store')}}"
BTW, It's not a validation error. Just fix your route.

Related

form input cleared after submit data using laravel fram work

I have multiple data base connection when I validate name of product I send message product name is exist before to view and here problem is appeared.
Message appeared in view but all form inputs is cleared.
How I recover this problem taking in consideration if product name not exist. validation executing correctly and if found error in validation it appeared normally and form input not cleared.
this my controller code.
public function add(Request $request)
{
// start add
if($request->isMethod('post'))
{
if(isset($_POST['add']))
{
// start validatio array
$validationarray=$this->validate($request,[
//'name' =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
'name' =>'required|alpha',
'price' =>'required|numeric',
]);
// check name is exist
$query = dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name']));
if(!$query) {
$product=new productModel();
// start add
$product->name = $request->input('name');
$product->save();
$add = $product->id;
$poducten = new productEnModel();
$poducten->id_product = $add;
$poducten->name = $request->input('name');
$poducten->price = $request->input('price');
$poducten->save();
$dataview['message'] = 'data addes';
} else {
$dataview['message'] = 'name is exist before';
}
}
}
$dataview['pagetitle']="add product geka";
return view('productss.add',$dataview);
}
this is my view
#extends('layout.header')
#section('content')
#if(isset($message))
{{$message}}
#endif
#if(count($errors)>0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form role="form" action="add" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="box-body">
<div class="form-group{{$errors->has('name')?'has-error':''}}">
<label for="exampleInputEmail1">Employee Name</label>
<input type="text" name="name" value="{{Request::old('name')}}" class="form-control" id="" placeholder="Enter Employee Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="text" name="price" value="{{Request::old('price')}}" class="form-control" id="" placeholder="Enter Employee Email Address">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="add" class="btn btn-primary">Add</button>
</div>
</form>
#endsection
this is my route
Route::get('/products/add',"produtController#add");
Route::post('/products/add',"produtController#add");
You can create your own custom validate function like below. I guess this should help you.
Found it from https://laravel.com/docs/5.8/validation#custom-validation-rules -> Using Closures
$validationarray = $this->validate($request,
[
'name' => [
'required',
'alpha',
function ($attribute, $value, $fail) {
//$attribute->input name, $value for that value.
//or your own way to collect data. then check.
//make your own condition.
if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$value))) {
$fail($attribute.' is failed custom rule. There have these named product.');
}
},
],
'price' => [
'required',
'numeric',
]
]);
First way you can throw validation exception manually. Here you can find out how can you figure out.
Second way (I recommend this one) you can generate a custom validation rule. By the way your controller method will be cleaner.

Parameter goes into array as the name of the field instead of the value

What am I trying to achieve?
I have "tasks" and each task can have multiple "notes", so when you select a Task and click notes, it takes you to a page with all the notes for the task in which you clicked.
Each note has a field called "task_id", so my problem is passing this task_id to the note.
I'm trying to pass it like this on the notes form:
<form method="POST" action="{{route('notes.store',$task)}}">
#include('notes.form')
</form>
And it goes into my controller
public function store(Request $r)
{
$validatedData = $r->validate([
'note' => 'required',
]);
$r['created_by'] = Auth::user()->user_id;
return $r;
/*
$note = Note::create($r->all());
return redirect('/notes')->with('store');
*/
}
But I return it to see how its going and I get this:
{"_token":"OmGrbYeQDl35oRnmewrVraCT0SHMC16wE4gD56nl","note":"363","created_by":4,"8":null}
That 8 at the end is actually the correct task id, but it appears as the name instead of the value.
What may be causing this?
This is my form view:
#csrf
<div class="col">
<div class="form-group">
<input type="text" class="form-control" name="note">
</div>
</div>
<div class="col-10">
<div class="form-group">
<button class="btn btn-success" type="submit">Add note</button>
<br><br>
</div>
</div>
These are my routes:
Route::get('/tasks/{task}/notes', ['as' => 'tasks.notes', 'uses' => 'NoteController#index']);
Route::get('/projects/{project}/tasks', ['as' => 'projects.tasks', 'uses' => 'ProjectController#seeTasks']);
Route::get('/projects/results','ProjectController#filter');
Route::get('/tasks/results','TaskController#filter');
Route::resource('projects','ProjectController');
Route::resource('clients','ClientController');
Route::resource('tasks','TaskController');
Route::resource('users','UserController');
Route::resource('notes','NoteController');
You are trying to pass the task_id as a route parameter, but your notes.store route has no route parameters.
Verb Path Action Route Name
POST /notes store notes.store
Adding the task_id as a hidden input should properly send it with the request:
<form method="POST" action="{{ route('notes.store') }}">
<input type="hidden" name="task_id" value="{{ $task->id }}">
#include('notes.form')
</form>

Passing Data through Return Redirect Back to Update Request

I am trying to allow a user to update their information after they have submitted a form, but did not check a certain box. Everything is within the same page and I am controlling the different modals by returning a message, which triggers a script to open the different modals.
For some reason, I can't seem to pass the ID or email through to the next step. Can anyone help with this?
Whenever, I try, I get the following error:
Undefined variable: leads
Any idea?
Thanks!!!
Files:
web.php
index.blade.php
LeadsController.php
Leads.php
Web.php
Route::post('/', [
'uses' => 'LeadsController#store',
'as' => 'leads.store'
]);
Route::patch('/{email}', [
'uses' => 'LeadsController#update',
'as' => 'leads.update'
]);
Index.blade.php
<html>
<div id="contact" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form id="form" class="form" action="/" method="post" accept-charset="utf-8">
{{ csrf_field() }}
<input type="email" name="email" value="{{ old('email') }}">
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#if(session()->has('message'))
<div id="sign_up" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form method="post" action="{{ route('leads.update', $leads->email) }}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#endif
</body>
</html>
LeadsController.php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->all);
} else {
try {
$leads = new Leads;
$leads->email = $request->email;
$leads->newsletter = $request->newsletter;
$leads->save();
if($request->newsletter == ''){
return redirect()->back()->with('message','sign up')->withInput($request->all)->with($leads->email, $request->get('email'));
}
if($request->newsletter == 'true'){
return redirect()->back()->with('success','success');
}
} catch (Exception $e) {
return response()->json(
[
'status' => false,
'error' => base64_encode($e->getMessage()),
],
Status::HTTP_INTERNAL_SERVER_ERROR
);
}
}
}
public function update($email)
{
$leads = Leads::find($email);
$leads->newsletter = $input('newsletter');
$leads->save();
return redirect()->back()->with('success','success');
}
Leads.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Leads extends Model
{
protected $table = 'my_renamed_table';
public $timestamps = false;
protected $fillable = ['email', 'newsletter'];
}
Thanks for all of your help and your questions! You helped push me in the right direction.
Here is how I solved it:
I had to correct myself in how I pushed the $email through to the view:
LeadsController
return redirect()
->back()
->with('message','sign up')
->withInput($request->all)
->with('email', $request->get('email'));
Notice how I'm sending the email through as 'email' here.
Then, I pushed the email through the view in the 2nd form like this:
index
<form method="post" action="{{ route('leads.update', session('email')) }}">
Then, finally, in order to capture the email again, use it to find the lead that I wanted, I had to drastically change the update:
public function update($email)
{
DB::table('my_renamed_table')
->where('email', $email)
->update(['newsletter' => Input::get('newsletter')]);
return redirect()->back()->with('success','success');
}
Thanks again!

Laravel 5.4 How to fix 'No query results for model'

Whenever I try to access /skills/add through an anchor in another page I get this error
The anchor that redirects to this page(with GET method) is:
<a class="btn icon-btn btn-success" href="/skills/add">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
Tried using dd("test") to test it out but won't even work.
This are my routes for skills/add this:
Route::put('/skills/add', 'SkillsController#add');
Route::get('/skills/add', 'SkillsController#addIndex');
Here are my functions in SkillsController
public function addIndex() {
if (Auth::check()) {
return view('skills.add');
} else {
return redirect('/home');
}
}
public function add(Request $request) {
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
$validator = Validator::validate($request->all(), $skillRules);
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
the skills.add view is this
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="/skills/add">
{{method_field('PUT')}}
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input name="name" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Not sure what happened, if someone in the future has this same problem, I literally just deleted and made manually thee controller, model and blade and it started to work. Not a lot of science or explain, sorry for that.
Change your route to named ones
Route::GET('/skills/add', 'SkillsController#addIndex')->name('addSkills');
Route::POST('/skills/add', 'SkillsController#add')->name('saveSkills');
and your blade to
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Skill</h1>
<form method="POST" action="{{route('saveSkills')"> //** Change this
{{csrf_field()}}
<div class="row">
<div class="col-lg-5">
<div class="form-group">
Name:
<input type="text" name="name" class="form-control"> //** Change this
</div>
</div>
//Remaining form groups
</div>
<div class="row">
<div class="col-lg-2">
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Skill</button>
<button type="button" class="btn btn-danger">Cancel</button>
</div>
</div>
</div>
</form>
</div>
#endsection
Change your anchor tag's href value to named route like
<a class="btn icon-btn btn-success" href="{{route('addSkills')}}">
<span class="glyphicon btn-glyphicon glyphicon-plus img-circle text-success"></span>
Add
</a>
and your controller
// SHOW ADD NEW SKILL FORM
public function addIndex() {
if (Auth::check()) {
return view('skills.add'); //view path is skills->add.blade.php
} else {
return redirect('/home');
}
}
//SAVE ADD NEW SKILL FORM DATA
public function add(Request $request) {
dd($request->name); //Check if value is getting
/*Sets validation rules for Skill object*/
$skillRules = [
'name' => 'required|max:25|regex:/[1-9a-zA-Z ]\w*/',
];
$validator = Validator::validate($request->all(), $skillRules);
if (Skills::where('name', '=', $request->name)->count() > 0) {
return redirect('/skills')->with('message', "EXISTS");
}
if ($validator == null) {
$newSkill = new Skills;
$newSkill->name = strtolower($request->name);
$newSkill->save();
return redirect('/skills')->with('message', "CREATED");
}
}
also add use App\RampUp\Skills; on top of controller
Sorry but there is no POST-route for <form method="POST" action="/skills/add">
maybe the POST is still executed.
On the other hand most Route errors could be resolved by clearing the cache (if present), rearranging the routes or put a group in between like
Route::group(['prefix' => 'skills'], function() {
Route::put('/add', 'SkillsController#add');
Route::get('/add', 'SkillsController#addIndex');
}

Laravel redirect() to is not generating the correct url

I would like to start by apologizing for the newbish question.
I'm in the process of making a simple CRUD controller on Laravel.
My create method is as follows:
public function create(Request $request)
{
$dummy = new Dummy();
$dummy->title = $request->title;
$dummy->content = $request->dummy_content;
$dummy->created_at = new \DateTime();
$dummy->updated_at = new \DateTime();
$dummy->save();
return redirect()
->route('index/view/', ['id' => $dummy->id])
->with('message', 'Dummy created successfully');
}
my view method:
public function view($id)
{
$dummy = Dummy::find($id);
return view('index/view', [
'dummy' => $dummy
]);
}
my corresponding routes:
Route::get('index/view/{id}', 'IndexController#view');
Route::post('index/create', 'IndexController#create');
and my form:
<form action="create" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="dummy_content" cols="80" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
When I submit my form I get the following exception:
InvalidArgumentException in UrlGenerator.php line 314:
Route [index/view/] not defined.
I've been stuck here for quite some time and I still can't figure out why I'm not generating my route properly.
What am I missing?
You are trying to call a route when instead you should call the controller. This will do the trick
return redirect()->action('IndexController#view', ['id' => $id])->with($stuff);
Also, i suggest you to define aliases to routes, so you could do something like
In your controller:
return Redirect::route('route_alias', ['id' => $id])->with($stuff);
In your routes:
Route::get('/index/view/{id}', [
'as' => 'route_alias',
'uses' => 'IndexController#view'
]);

Categories