I have problem with my store function in Laravel 9 - php

basically every time I submit the form, the page refresh, and no items are stored in the DB. Here's the code.
PodcastController
public function store(Request $request) {
$request->validate([
'title' => 'required',
'description' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,webp|max:2048',
'audio' => 'audio|mimes:audio/mpeg',
'category' => 'required',
]);
if ($request->image) {
$imageName = uniqid() . '.' . $request->image->extension();
$request->image->move(public_path('podcast/images'), $imageName);
}
if ($request->audio) {
$audioName = uniqid() . '.' . $request->audio->extension();
$request->audio->move(public_path('podcast/audios'), $audioName);
}
Podcast::create([
'title' => $request->title,
'description' => $request->description,
'image' => $imageName,
'audio' => $audioName,
'category' => $request->category,
]);
return redirect()->route('podcast.list')->with('Success', 'Podcast Created!');
}
Route
Route::resource(
'podcasts',
App\Http\Controllers\PodcastController::class
);
create.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="col-md-6">
<form action="{{ route('podcasts.store') }}" method="POST" enctype=multipart/form-data>
#csrf
<input class="form-control" type="text" name="title" placeholder="title">
<input class="form-control mt-4" type="textarea" name="description" placeholder="description">
<select name="category" class="form-control mt-4">
<option value="select" disabled>Are you a Creator or a User?</option>
<option value="news">News</option>
<option value="music">Music</option>
</select>
<label for="image" class="mt-3">Image</label>
<input type="file" class="form-control" id="image" name="image">
<label for="audio" class="mt-3">Audio</label>
<input type="file" class="form-control" id="video" name="audio">
<button type="submit" class="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
#endsection
The page keep refreshing everytime I run submit. I don't know where is the problem.

You catching a failure while validating. After catching these validate errors, you should develop your code what to do.
https://laravel.com/api/9.x/Illuminate/Validation/ValidationException.html
try {
$request->validate([
'title' => 'required',
'description' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,webp|max:2048',
'audio' => 'audio|mimes:audio/mpeg',
'category' => 'required',
]);
} catch (\Illuminate\Validation\ValidationException $e) {
// do something...
dd($e->errors());
}

Related

Laravel 302 when i do a validation

When I do post form in laravel and then validate it from the controller I get this response :
302 found
nothing useful, I`ve tried everything but nothing worked with me.
My Form blade :
<form action="{{route('newitem')}}" method="post">
#csrf
<div class="mb-3">
<label for="item name" class="form-label">Email address</label>
<input type="text" class="form-control" id="item name" name="item_name" >
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" class="form-control" id="price" name="item_price">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
my controller :
public function new_item(Request $rq){
$validated = $rq->validate(
[
'item_name' => 'required|string|min:4|max:90',
'item_desc' => 'string|min:4|max:90',
'item_price' => 'required|integer|min:4'
]
);
UsrsItem::create([
'item_name' => $validated->item_title,
'item_price' => $validated->item_price,
]);
}
I hope someone can help me with that :<
Contrroller Code
public function new_item(Request $rq){
$validated = $rq->validate(
[
'item_name' => 'required|string|min:4|max:90',
'item_desc' => 'string|min:4|max:90',
'item_price' => 'required|integer|min:4'
]
);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
UsrsItem::create([
'item_name' => $validated->item_title,
'item_price' => $validated->item_price,
]);
return response()->json(['success'=>'Record is successfully added']);
}
Put This In Blade File
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif

CodeIgniter 4 Error Validation Not Reading

I'm working on a contact form with Codeigniter 4 and SQL Database. The form will submit through the button, so whenever it is clicked, it is validating, and if all of the fields are filled out, it has no trouble displaying the message and save the information to the database, but when the fields are empty, it does not display the error message, and it continues to state that the file does not exist.
Well, I'm stuck with the error message now. I'm not sure what wrong with the code. Am I missing something?
Can anybody help me with this? I appreciate all the help I can get.
Below are my codes:
App/config/Routes.php
$routes->get('contact', 'Contact::contact');
$routes->post('contact/save', 'Contact::save');
App/Controller/Contact.php
<?php
namespace App\Controllers;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct()
{
helper(['url', 'form']);
}
//CONTACT PAGE
public function contact()
{
$data = [
'meta_title' => 'Contact | MFD',
];
return view('page_templates/contact', $data);
}
//SAVE
public function save()
{
$validation = $this->validate([
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Your full name is required'
]
],
'email' => [
'rules' => 'required|valid_email|is_unique[users.email]',
'errors' => [
'required' => 'Email is required',
'valid_email' => 'You must enter a valid email',
]
],
'title' => [
'rules' => 'required',
'errors' => [
'required' => 'Title is required',
]
],
'content' => [
'rules' => 'required',
'errors' => [
'required' => 'Content is required',
]
],
]);
if (!$validation) {
return view('contact', ['validation' => $this->validator]);
} else {
// Let's Register user into db
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$title = $this->request->getPost('title');
$content = $this->request->getPost('content');
$values = [
'name' => $name,
'email' => $email,
'title' => $title,
'content' => $content,
];
$contactModel = new ContactModel();
$query = $contactModel->insert($values);
if ($query) {
return redirect()->to('contact')->with('success', 'Your message are successful sent');
} else {
return redirect()->to('contact')->with('fail', 'Something went wrong');
}
}
}
}
App/Views/page_templates/contact.php
<form action="<?= base_url('contact/save'); ?>" method="post" role="form" class="php-email-form">
<?= csrf_field(); ?>
<?php if (!empty(session()->getFlashdata('error'))) : ?>
<div class="alert alert-danger"><?= session()->getFlashdata('error'); ?></div>
<?php endif ?>
<?php if (!empty(session()->getFlashdata('success'))) : ?>
<div class="alert alert-success"><?= session()->getFlashdata('success'); ?></div>
<?php endif ?>
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" value="<?= set_value('name'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'name') : '' ?></span>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" value="<?= set_value('email'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'email') : '' ?></span>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'title') : '' ?></span>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="content" rows="5" wrap="hard" placeholder="Message"></textarea>
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'content') : '' ?></span>
</div>
<div style="height: 10px;"></div>
<div class="text-left button">
<button type="submit" name="submit">Send Message</button>
</div>
<div style="height: 10px;"></div>
</form>
Okay, I have fixed the problem with my code. It's really is a small mistake or I could say careless mistake haha feel so dumb right now but all that I need to change and make it work.
Is this part: return view('contact', ['validation' => $this->validator]);
Instead of doing it like that I actually miss placing the file to call the view page properly so the code I only added my the folder name that is
page_templates
and if I include it in the code it should look like this:-
return view('page_template/contact', ['validation' => $this->validator]);
and it works after that haha.

The 0 field is required. Laravel 5.5 Validation error

Am having a "The 0 field is required." error while trying save data into database when I have no field called 0. without validation from the Controller, the data saves but if I validate even just one field out of the six field I want to validate, I still get the error. How do I solve the issue. Please help out here is my view
<form method="post" action="{{ url('agent/add_tenantProperty') }}" data-toggle="validator">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtMovieTitle">Tenant</label>
<select id="ddlGenge" class="form-control" name="tenant_id" required="">
#foreach($tenants as $tenant)
<option value="{{ $tenant->id }}">
{{ $tenant->designation }} {{ $tenant->firstname }} {{ $tenant->lastname }}
</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="ddlGenge">Asset Category</label>
<select id="ddlGenge" class="form-control" name="asset_id" required="">
<option>Choose a Property</option>
#foreach($assets as $asset)
<option value="{{ $asset->id }}">{{ $asset->category }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtDirector">Asset description</label>
<select id="ddlGenge" class="form-control" name="description" required="">
<option>Choose a Description</option>
#foreach($assets as $asset)
<option value="{{ $asset->description }}">{{ $asset->description }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtProducer">Location</label>
<select id="ddlGenge" class="form-control" name="address" required="">
<option>Choose an Address</option>
#foreach($assets as $asset)
<option value="{{ $asset->address }}">{{ $asset->address }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtWebsite">Standard price</label>
<input id="txtWebsite" type="text" class="form-control" name="price" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtWriter">Date</label>
<input id="txtWriter" type="date" class="datepicker form-control" name="occupation_date"
required="">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-outline btn-primary pull-right">Submit</button>
<br/>
</form>
and my controller
public function store(Request $request)
{
//validation
$this->validate($request, array([
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]));
//create and save new data
$tenantProperty = New TenantProperty();
$tenantProperty->tenant_id = $request->tenant_id;
$tenantProperty->asset_id = $request->asset_id;
$tenantProperty->description = $request->description;
$tenantProperty->address = $request->address;
$tenantProperty->price = $request->price;
$tenantProperty->occupation_date = $request->occupation_date;
$tenantProperty->save();
//redirect
return redirect('agent/tenantProperty_list');
}
with the route as follows
Route::get('add_tenantProperty', 'TenantPropertyController#create')->name('/add_tenantProperty');
Route::post('add_tenantProperty', 'TenantPropertyController#store');
When you just write $request, it passes the entire request object but the validate function expect both the arguments to be arrays.
So make a little change and you will be good to go:
$this->validate($request, array( // Removed `[]` from the array.
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
));
The above answer is correct, this is another way to solve the validation problem on laravel 5.5 I asked
$validation = validator::make($request->all(), [
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]);
For more information visit https://laravel.com/docs/5.5/validation#manually-creating-validators
$request->validate([
'0'=>'',
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',]);

Laravel create and auth login

I have a simple registration where validation passes, but create doesn't fill up fullname and phone(I checked they are passed - by echoing).
I also tried by using request()->input('fullname'); but I got same result.
For login after storing values this auth()->login($user) and auth()->attempt() both fails.
I don't know since uniqid for password is same as stored....
public function register(Request $request) {
$this->validate($request, [
'fullname' => 'required|min:2|max:255',
'email' => 'required|email|unique:users',
'phone' => 'required'
]);
$passcode = uniqid();
$user = User::create([
'fullname' => $request->fullname,
'email' => $request->email,
'password' => bcrypt($passcode),
'phone' => $request->phone
]);
if(User::sendEmail($passcode, $request->email, $request->fullname)) {
if (auth()->login($user)) {
session()->flash('user', 'You have been logged in..');
session()->flash('data', request());
return redirect()->route('dashboard');
}
session()->flash('login', 'Not logged in.');
}
return redirect()->back();
}
<form action="{{ route('register') }}" method="POST">
{{ csrf_field() }}
<input type="text" name="fullname" placeholder="Full name">
<input type="text" name="email" placeholder="E-mail">
<input type="text" name="phone" placeholder="Phone">
<button type="submit">Continue</button>
</form>

Laravel 5.4 - Duplicate row inserted

I have been using Laravel for a couple years and I'm stumped on this one. Using Laravel 5.4 with voyager. I have my own controller outside of the BREAD controller
Form:
<form method="POST" action="/admin/invites" accept-charset="UTF-8" class="form-edit-add">
<input name="_token" type="hidden" value="QgLgj5tG4RfD2CxCsqE2Qn5jcWfwQhsk5THT30vO">
<div class="panel-body">
<div class="form-group">
<label for="name">Business</label>
<input class="form-control" placeholder="Business Name" name="business_id" type="text">
</div>
<div class="form-group">
<label for="body">Referral Name</label>
<input class="form-control" placeholder="Referral Name" name="referral_name" type="text">
</div>
</div>
<input class="btn btn-primary width-100 mb-xs" type="submit" value="Save">
</form>
web routes:
Route::resource('/admin/invites', 'InviteController');
Controller:
public function store(Requests\InviteRequest $request)
{
DB::table('invites')->insert(
[
'user_id' => Auth::user()->id,
'business_id' => $request->business_id,
'referral_name' => $request->referral_name,
'url_token' => str_random(16)
]
);
return redirect('/admin/invites')->with([
'message' => "Successfully Added New",
'alert-type' => 'success',
]);
}
When I submit it creates 2 rows in the database. I don't have duplicate routes or controllers. My Request file is empty. I have an ID in the table that is auto increment with primary index.
Any thoughts or troubleshooting tips?
I think the main point you are missing here is that Voyager calls its store() twice. First, through AJAX to validate the fields and then again by normal form submit to store the BREAD to the database.
Take a look at the default store() implementation in Voyager:
public function store(Request $request)
{
$slug = $this->getSlug($request);
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
Voyager::canOrFail('add_'.$dataType->name);
//Validate fields with ajax
$val = $this->validateBread($request->all(), $dataType->addRows);
if ($val->fails()) {
return response()->json(['errors' => $val->messages()]);
}
if (!$request->ajax()) {
$data = $this->insertUpdateData($request, $slug, $dataType->addRows, new $dataType->model_name());
return redirect()
->route("voyager.{$dataType->slug}.edit", ['id' => $data->id])
->with([
'message' => "Successfully Added New {$dataType->display_name_singular}",
'alert-type' => 'success',
]);
}
}
Notice the if (!$request->ajax()) condition, the first AJAX call would bypass that but the second call would get into it and store to the database.
So in short, you have to follow the same structure in your store() method. Perform your validations first. Then when it's time to save, put that code into the if (!$request->ajax()) condition.
your form has some issues:
<label for="name">Business</label>
<input class="form-control" placeholder="Business Name" name="business_id" type="text">
change label for to for="business_id
<label for="body">Referral Name</label>
<input class="form-control" placeholder="Referral Name" name="referral_name"
</div>
change label for to for="referral_name
change your store method to this:
public function store(Requests\InviteRequest $request) {
$this->validate($request, array(
'user_id' => 'required',
'business_id' => 'required',
'referral_name' => 'required',
));
DB::table('invites')->insert([
'user_id' => $request->user_id,
'business_id' => $request->business_id,
'referral_name' => $request->referral_name,
'url_token' => str_random(16),
// If you don't use timestamp delete these lines below
'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
'updated_at' => Carbon::now()->format('Y-m-d H:i:s'),
]);
return redirect('/admin/invites')->with([
'message' => "Successfully Added New",
'alert-type' => 'success',
]);
}
see if it works.

Categories