Cannot find errors returned by validate method - laravel

I am using the validate method to validate user input and when I post a form with errors, I get redirected to the previous page but the form is not repopulated and the errors are not showing. I have include a partial view for showing errors in the page with the form. The partial view is:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors as $error)
<li> {{ $error }} </li>
#endforeach
</ul>
</div>
#endif
the action method in the controller is:
public function store(Request $request)
{
$request->validate([
'product_name' => 'required',
'age' => 'required',
'product_code' => 'required|alpha_num',
'price' => 'required|numeric',
]);
$product=new Product();
The view with the form is:
#section('content')
<div class="container">
#include('partials.errors')
<form action="/products/create" method="POST">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
#csrf
<div class="form-group">
<label>Product Name</label>
<input name="product_name" type="text" class="form-control">
</div>
<div class="form-group">
<label>Age</label>
<input name="age" type="text" class="form-control">
</div>
<div class="form-group">
<label>Gender</label>
<select class="form-control" name="gender">
<option>
Male
</option>
<option>
Female
</option>
Unisex
</option>
</select>
</div>
<div class="form-group">
<label>Product Code</label>
<input name="product_code" type="text" class="form-control">
</div>
<div class="form-group">
<label>Price</label>
<input name="price" type="text" class="form-control">
</div>
<div class="form-group">
<label>Product Category</label>
<select class="form-control" name="category_name">
#foreach ($product_categories as $product_category)
<option>{{ $product_category->category_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Brand</label>
<select class="form-control" name="brand_name">
#foreach ($brands as $brand)
<option>{{ $brand->brand_name }}</option>
#endforeach
</select>
</div>
<button class="btn btn-primary" type="submit">Create</button>
</form>
</div>
#endsection
when I post a failed form, I get redirected to the view with the form but the form is not repopulated with the input that I entered. additionally, the erros are not shown but just an empty red div. According to a book I read, if the data isn’t valid, the validate method throws a ValidationException and the exception will return a redirect to the previous page, together with all of the user input and the validation errors. I am new to laravel.

You should use old() method to keep repopulate entered value in input field like below
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
To show validation error you have to add errors in each field for example like below
#error("product_code")
<div class="invalid-feedback">{{ $message }}</div>
#enderror
You can read more about old method here
https://laravel.com/docs/8.x/requests#retrieving-old-input
For validation error
https://laravel.com/docs/8.x/validation#the-at-error-directive

First, the CSRF token:
If you check the docs you'll see that you have 2 options how to add it:
#csrf
<!-- Equivalent to... -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
You are doing both, remove one of them.
Second, the old input:
You are missing the old input call. For example:
<input name="product_code" type="text" class="form-control" value="{{ old('product_code') }}">
Last, the errors:
You are doing it correctly.
If is still not working, check that your route is using the middleware web.

Related

How to update or create at same time in laravel

``I had one page on that I'm Showing data from two table with left join and also edit button in front of every column when user click to edit button ,it goes a different page where user can update input fields but at the same time i want if some field is not showing data we can create data only when both the id of tables are matching
By this i can easily update but i can't create it shows error
Attempt to assign property "SchemeId" on null
Controller
public function SchConfigrationUpdate(Request $request, $SchemeId)
{
$scheme = tbl_schemeconfigration::find($SchemeId);
$scheme->SchemeId = $request->input('SchemeId');
$scheme->MerchantCode = $request->input('MerchantCode');
$scheme->BankAccountNumber = $request->input('BankAccountNumber');
$scheme->BankAccountIFSC = $request->input('BankAccountIFSC');
$scheme->save();
return redirect()
->back()
->with('success', 'Scheme Update Successfully');
}
**view**
<form action="{{ url('SchConfigration-update/' . $user->SchemeId) }}" method="post"
enctype="multipart/form-data">
#csrf
#method('PUT')
<input type="hidden" name="SchemeId" value="{{ $user->SchemeId }}">
<div class="form_row">
<div class="form_item">
<label>Scheme Name</label>
<input type="text" id="SchemeId" name="SchemeId"
placeholder="Enter scheme name" class="form-control" required
value="{{ $user->SchemeId }}">
{{-- value="{{ request()->SchemeId }}" --}}
{{-- if we want to pass scheme name just pass $user->SchemeName --}}
</div>
<div class="form_item">
<label>Merchant Code</label>
<input type="text" id="MerchantCode" name="MerchantCode"
placeholder="Enter Merchant Code" class="form-control" required
value="{{ $user->MerchantCode }}">
</div>
</div>
<div class="form_row">
<div class="form_item">
<label>Bank Account Number</label>
<input type="text" id="BankAccountNumber" name="BankAccountNumber"
placeholder="Bank account Number" maxlength="17" class="form-control" required
value="{{ $user->BankAccountNumber }}">
</div>
<div class="form_item">
<label>Bank Account IFSC</label>
<input type="text" id="BankAccountIFSC" name="BankAccountIFSC"
placeholder="Bank account IFSC" maxlength="11" class="form-control" required
value="{{ $user->BankAccountIFSC }}">
</div>
</div>
<div class="btn_row">
<input type="submit" value="submit" class="primary_btn">
<a class="btn btn-primary" href="{{ url('SchConfigration') }}"
role="button">Back</a>
</div>
</form>
`
Try This
public function SchConfigrationUpdate(Request $request, $SchemeId)
{
$scheme = tbl_schemeconfigration::updateOrCreate(
['SchemeId' => $request->input('SchemeId')],
[
'MerchantCode' => $request->input('MerchantCode'),
'BankAccountNumber' => $request->input('BankAccountNumber'),
'BankAccountIFSC' => $request->input('BankAccountIFSC')
]
);
return redirect()
->back()
->with('success', 'Scheme Update Successfully');
}

How to solved Invalid argument supplied for foreach()

I am tired to solve the problem. I will see that everything is ok. but maybe there is any wrong. why that showing Invalid argument supplied for foreach(). What is wrong here? Please solved it.
<form action="{{route('send.email.noactiveusers')}}" method="post">
#csrf
<div class="form-group row">
<label class="col-form-label col-lg-2">To All No Active users</label>
<div class="col-lg-10">
<select multiple="multiple" class="form-control select" name="noactivemail" data-fouc>
<optgroup label="Subscribed users">
#foreach($client as $val)
#if($val->NoActivities($val->last_deposit)==="yes")
<option value="{{$val->email}}" selected>{{$val->email}}</option>
#else
#endif
#endforeach
</optgroup>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-lg-2">Subject:</label>
<div class="col-lg-10">
<input type="text" name="subject" maxlength="200" value="No activities for over 3 months"
class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-form-label col-lg-2">Message:</label>
<div class="col-lg-10">
<textarea type="text" name="message" rows="4" class="form-control tinymce">We see that no activities over 3 months on your account. If you want to stay active in your account then please deposit on your account within 7 days. Otherwise, your account deactivated.</textarea>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn bg-dark">Send<i class="icon-paperplane ml-2"></i></button>
</div>
</form>
public function SendEmailtoNoActiveUsers(Request $request)
{
$set=Settings::first();
foreach ($request->noactivemail as $email) {
$user=User::whereEmail($email)->first();
send_email($user->email, $user->name, $request->subject, $request->message);
}
return back()->with('success', 'Message sent!.');
}
you are using multiple select but you are not using an array to send those selected values. when you are sending multiple values with the same name attribute you have to make it an array. so just update your select with
<select multiple="multiple" class="form-control select" name="noactivemail[]" data-foucs>
this will send an array named noactivemail with your form request. and you can then iterate in the controller.
foreach ($request->noactivemail as $email) {
$user = User::where('email', $email)->first();
send_email($user->email, $user->name, $request->subject, $request->message);
}

Update single field in a Profile Update Form in Laravel 5

I am trying to update a single field in my user profile form section in the Laravel app.
I can save fields correctly in DB but input values and placeholders are taking wrong values. In every hit Save, the values doesn' change, and they are taken from the last listed user profile details. In my case this is user#3. The problem is when I log in with the user's #1 credentials, value and placeholder are taken from user #3. When I log in with user #2, again from user #3. Only values of user#3 are correct and I can manipulate it with no issues for both fields.
When i update the profile fields with user#1 it saves the entered one filed, but because the 2nd filed inherits the user#3 input details it saves it in field 2 of user#1 which makes a wrong entry. I can't leave null in those fields by default. My mass assignment is guarded.
How can save/update just a single field in the blade template without affecting the other fields in the form?
My routes:
Route::get( '/profile', 'userController\\profileEdit#profileEdit')->name('profileEdit');
Route::post('/profile', 'userController\\profileEdit#update')->name('update');
My controller:
namespace App\Http\Controllers\userController;
use App\Model\Hause_users;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class profileEdit extends Controller
{
function profileEdit (Request $request){
$user = Hause_users::all();
$name = $request->session()->get('name');
$request->session()->keep([request('username', 'email')]);
return view('frontview.layouts.profile',['user'=>$user])->with('username' , $name );
}
function update (Request $request){
$user = Hause_users::where('username', $request->session()->get('name'))->first();
$user->fill(['email' => request('Email')]) ;
$user->save();
$user->phone;
//dd($user->phone->phone);
if ($user->phone === null) {
$user->phone->phone->create(['phone' => request('tel')]);
}
else{
$user->phone->update(['phone' => request('tel')]);
}
return back()->withInput();
}
Blade file: `
#extends('frontview.layouts.userView')
#extends('frontview.layouts.default')
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#section('title')
#endsection
#section('content')
#foreach($user as $v )
#endforeach
<h2 class="form-group col-md-6">Здравей, {{$username }} </h2>
<form class = "pb2" method="POST" name = 'profile' action='profile' >
{{ csrf_field()}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="email" class="form-control" name = "Email" id="inputEmail4"
value="{{$v['Email']}}"
placeholder="{{$v->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$v->phone['phone']}}"
placeholder="{{$v->phone['phone']}}"
id="example-tel-input" >
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputCity">Град</label><input type="text" class="form-control" id="inputCity">
<label for="inputCity">Квартал</label><input type="text" class="form-control" id="inputCity">
</div>
{{--<div class="col-md-6" >--}}
{{--<label for="image">Качи снимка</label>--}}
{{--<input type="file" name = "image">--}}
{{--<div>{{$errors->first('image') }}</div>--}}
{{--</div>--}}
</div>
{{--<div ><img src="https://mdbootstrap.com/img/Photos/Others/placeholder-avatar.jpg"--}}
{{--class="rounded-circle z-depth-1-half avatar-pic" alt="example placeholder avatar">--}}
{{--</div>--}}
{{--<div class="d-flex justify-content-center">--}}
{{--<div class="btn btn-mdb-color btn-rounded float-left">--}}
{{--<span>Add photo</span>--}}
{{--<input type="file">--}}
{{--</div>--}}
{{--</div>--}}
{{--</div>--}}
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Запомни ме!
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Запази</button>
</form>
#endsection
#section('name')
{{ $username }}
#endsection
Output summary:
On img#1 are the correct entry details . This is other section not the Profile edit one. Currently loged user is U#1 but as you can see on image 2, values and placeholder of both fields are for the U#3. When i hit the blue button U#1 saves the untouched filed input of U#3. Same is when i log in with U#2.
Actually the answer here is quite simple. What i am doing wrong is that i am not passing the value of the currently logged user to the view correctly. On my profileEdit method i was using $user = Hause_users::all(); and then looping trough all id's into the view and then fetching every field. But because the view doesn know which user passes the data, the foreach always returns the last user id from the array with its input, no matter which user is currently logged in. Then the data was overridden with wrong inputs.
The solution is also simple.
Instead of $user = Hause_users::all();
i have used
$user = Hause_users::where('username', $request->session()->get('name'))->first();
and then into view i was objecting the $user variable without any loops like this:
<form class = "pb2" method="POST" name = 'profile' action='profile' >
<input type="hidden" name="_token" value="{{ csrf_token() }}">
{{--<input type="hidden" name="_method" value="PATCH">--}}
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputEmail4">Поща</label>
<input type="Email" class="form-control" name = "Email" id="inputEmail4"
value="{{$user->Email}}"
placeholder="{{$user->Email}}">
</div>
<div class="form-group col-md-6">
<label for="inputPassword4">Промени Парола</label>
<input type="password" class="form-control" id="inputPassword4" placeholder="Парола">
</div>
</div>
<div class="form-group">
<label for="inputAddress">Address</label>
<input type="text" class="form-control" name = "Adress" id="inputAddress" placeholder="Снежанка 2">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label for="inputAddress">Телефон</label>
<input class="form-control" type="text" name = 'tel' value="{{$user->phone['phone']}}"
placeholder="{{$user->phone['phone']}}"
id="example-tel-input" >
Basically this is a detailed explanation to all that not using the built in Auth system of Laravel

Laravel Request Input is not usable data

Ok maybe this is a noob laravel question but when I'm trying to store data from a form I used a $request->input in a query to get a needed field for insert but the query will not run. Note: does run if I just set something like $project_id = 6.
public function store(Request $request)
{
$project_id = $request->input('project_id');
$company = Project::where('id', $project_id)->first();
if(Auth::check()){
$task = Task::create([
'name' => $request->input('name'),
'project_id' => $project_id,
'company_id' => $company->id,
'days' => $request->input('days'),
'hours' => $request->input('hours'),
'user_id' => Auth::user()->id
]);
if($task){
return redirect()->route('tasks.index')
->with('success' , 'Task created successfully');
}
}
return back()->withInput()->with('errors', 'Error creating new task');
}
Note:
I've tried a couple different things I've found online like $project_id = $request->project_id or $project_id = $request['project_id']
Is request->input just used for inserts and can't be used as a normal varible?
Update: here is the create.blade form it's coming from
#extends('layouts.app')
#section('content')
<div class="row col-md-9 col-lg-9 col-sm-9 pull-left " >
<h1>Add a Task </h1>
<!-- Example row of columns -->
<div class="col-md-12 col-lg-12 col-sm-12" style="background: white; margin: 10px;" >
<form method="post" action="{{ route('tasks.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="project-name">Name<span class="required">*</span></label>
<input placeholder="Enter name"
id="project-name"
required
name="name"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-days">Days Taken<span class="required"></span></label>
<input
id="task-days"
required
name="days"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<div class="form-group">
<label for="task-hours">Hours Taken<span class="required"></span></label>
<input
id="task-hours"
required
name="hours"
type="number"
spellcheck="false"
class="form-control"
/>
</div>
<input
class="form-control"
type="hidden"
name="project_id"
value="{{ $project_id }}"
/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{$project_id}}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
<div class="form-group">
<input type="submit" class="btn btn-primary"
value="Submit"/>
</div>
</form>
</div>
</div>
<div class="col-sm-3 col-md-3 col-lg-3 col-sm-3 pull-right">
<div class="sidebar-module sidebar-module-inset">
<h4>Actions</h4>
<ol class="list-unstyled">
<li>All tasks</li>
</ol>
</div>
</div>
#endsection
Let's examine your <form> below:
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project_id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#endif
In this code, you have a hidden input with the name "project_id", and if $projects is not null, you also have a select with the name "project_id". Having multiple elements with the same name is invalid, and can cause issues.
Secondly, in this line:
<option value="{{ $project_id }}">{{ $project->name }}</option>
$project_id is the same value you have in the hidden input above. When you're looping over $projects, this should be $project->id:
<option value="{{ $project->id }}">{{ $project->name }}</option>
Lastly, make sure that $project_id is a valid value if you're going to send it, and consider adjusting your logic to only send the hidden input if $projects is null:
#if($projects != null)
<div class="form-group">
<label for="company-content">Select Project</label>
<select name="project_id" class="form-control">
#foreach($projects as $project)
<option value="{{ $project->id }}">{{ $project->name }}</option>
#endforeach
</select>
</div>
#else
<input class="form-control" type="hidden" name="project_id" value="{{ $project_id }}"/>
#endif
With all that adjusted, you should be able to retrieve the expected value with $request->input("project_id")

Laravel | Delete function - how to delete photo from calendar's event

How can I remove photo from calendar's event in edit calendar's event view? In list of events I did delete method and it works. Now when I try to do the same in edit.blade.php it gives error:
Call to a member function photos() on null
I have two tables in relationship one calendar to many photos, file upload works, but I stucked on edit part.
Look at my controller function:
public function deletePhoto(CalendarRepository $calRepo, $id)
{
$calendars = $calRepo->find($id);
$calendars->photos($id)->delete();
return redirect()->action('CalendarController#edit');
}
and here is fragment of edit.blade.php:
<div class="form-group">
<label for="photo">Photo:</label>
<div class="row">
#foreach(($calendar->photos) as $photo)
<div class="col-md-3">
<div class="admin-thumbnail">
<img class="img-responsive" src="/storage/{{ $photo->filename }}" style="width:100px; height:auto;"/>
</div>
<i class="fas fa-times"></i>Remove
</div>
#endforeach
</div>
</div>
I need to remove photo from Photo table and redirect to edit.blade.php (about the specific event id of the calendar)
Thanks for any help.
EDIT:
<div class="card-body">
<form action="{{ action ('CalendarController#editStore')}}" method="POST" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{csrf_token() }}"/>
<input type="hidden" name="id" value="{{ $calendar->id }}"/>
<input type="hidden" name="_token" value="{{csrf_token() }}"/>
<div class="form-group">
<label for="photo">Photo:</label>
<div class="row">
#foreach(($calendar->photos) as $photo)
<div class="col-md-3">
<div class="admin-thumbnail">
<img class="img-responsive" src="/storage/{{ $photo->filename }}"/>
</div>
<form method="POST" action="{{ route('photo.delete', ['calendar' => $calendar, 'photo' => $photo]) }}">
#csrf
#method("DELETE")
<a onClick="return confirm('Are you sure?')"><i class="fas fa-times"></i>Remove</a>
</form>
</div>
#endforeach
</div>
</div>
<div class="form-group">
<label for="header">Header</label>
<input type="text" class="form-control" name="header" value="{{ $calendar->header }}"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" value="{{ $calendar->description }}"/>
</div>
<div class="form-group">
<label for="date">Date</label>
<input type="date" class="form-control" name="date" value="{{ $calendar->date }}"/>
</div>
<input type="submit" value="Save" class="btn btn-primary"/>
</form>
</div>
You use the same $id to find the photo and the calendar instance.
GET request is not recommended for deleting a resource, so a better approach would be in your routes you can have something like this:
Route::delete('photo/{photo}', 'PhotosController#delete')->name('photo.delete');
Then in your view, you should surround the button with a Form, for example:
<form method="POST" action="{{ route('photo.delete', $photo) }}">
#csrf
#method("DELETE")
<a onClick="return confirm('Are you sure?')"><i class="fas fa-times"></i>Remove</a>
</form>
Then your confirm function in JS should submit the form if the user accepts to delete the photo. And also remember to return false as default in the confirm function so it does not submits the form by default.
Your controller will then be:
public function delete(Photo $photo)
{
$photo->delete();
return redirect()->back();
}
--- EDIT
Route::delete('calendar/{calendar}/photo/{photo}', 'CalendarController#deletePhoto')->name('photo.delete');
and the action in the form can be:
{{ route('photo.delete', ['calendar' => $calendar, 'photo' => $photo]) }}
The method in the controller:
public function deletePhoto(Calendar $calendar, Photo $photo)
{
$calendar->photos()->where('id', $photo->id)->delete();
return redirect()->action('CalendarController#edit');
}

Resources