How to prompt message if field is empty, Laravel - php

So I have this field for search and image field , in search form I have a button submit it works but when I clicked it and there's no input in the input field it shows error and in the image field if I don't add an image it shows error... Do I solve this through a prompt message? to let the users know that that field is empty. Here's my code for search
building.blade.php
{!! Form::open(['method'=> 'GET','url'=>'offices','role'=>'search']) !!}
<div class="input-group col-xs-4 col-md-6" >
<input type="text" name="search" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button type="submit" class="btn btn-info btn-md"><span class="glyphicon glyphicon-search"></span> Search
</button>
</span>
</div>
{!! Form::close()!!}
OfficeController.php
public function index()
{
$search = \Request::get('search');
$offices = Office::where('name','LIKE','%'.$search.'%')->get();
return view('search',compact('offices','search'));
}
createbuilding.blade.php
{!! Form::label('Building Photo') !!}
{!! Form::file('buildingpics',array('onchange'=>'previewFile()')) !!}
<img src="../assets/imageholder.png" id="previewImg" style="height:300px; width:300px;" alt="">
</div>
<div class="form-group">
<button type="submit" class="btn btn-default btn-md">
<span class="glyphicon glyphicon-plus"></span> Add Building
</button>
<!-- {!! Form::submit('Create Building',
array('class'=>'btn btn-primary')) !!} -->
<span class="glyphicon glyphicon-arrow-left"></span> Back
</div>
</div>
{!! Form::close() !!}
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#previewImg');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>
#endsection
#section('scripts')
#endsection

You can validate it by using laravel validate method in your controller just put the validate code in your controller like
$this->validate($request, [
'field_name1' => 'required',
'field_name2' => 'required',
]);
and in your view just popup the error message so if the user is not fill the field or the field is empty then it show the error message on the submit of the request so user can easily understand what is required.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!--error ends-->
Hope this code will help you to shortout the what you want.

You can either go with HTML5 required attribute like so
<input type="text" name="search" class="form-control" placeholder="Search..." required>
or
You can user Laravel's Form Request Validation
https://laravel.com/docs/5.5/validation#form-request-validation

Related

Laravel resource store method is being redirected to destroy method

I have a resource route
Route::resource('climb-excluded','CexcludedController',['only'=>['store','update','destroy']]);
And my code in view to save data
<div class="col-lg-4">
<form class="form" method="POST" action="{{ route('climb-excluded.store') }}">
{{ csrf_field() }}
<div class="card">
<div class="card-head style-primary">
<header>Add item</header>
</div>
<div class="card-body floating-label">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name">
<label for="name">Name</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<button type="submit"
class="btn btn-block btn-success ink-reaction">
Add
</button>
</div>
</div>
</div>
</div>
A button to destroy data:
{!! Form::open( array('route'=>array('climb-excluded.destroy', $excluded->id),
'method'=>'DELETE')) !!}
<button type="submit"
class="btn ink-reaction btn-floating-action btn-sm btn-danger "
rel="tooltip"
title="Delete">
<i class="fa fa-trash-o" aria-hidden="true"></i>
</button
{!! Form::close() !!}
Store method form controller:
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required|max:255'
]);
$excluded = new Cexcluded;
$excluded -> name = $request->name;
$excluded->save();
//redirect to
Session::flash('success','New item sucessfully added !');
return back()->withInput(['tabs'=>'second4']);
}
Destroy method form controller:
public function destroy($id)
{
$trekExcluded = Cexcluded::find($id);
$trekExcluded->tours()->detach();
$trekExcluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return back()->withInput(['tabs'=>'second4']);
}
The trouble/bug that I'm facing is I can insert first row into table successfully. But when I go for the second one, the store method is somehow redirected to destroy method and deletes the first inserted row also. While I've clearly declared store method in action attribute of the form.
FYI: Both routes exists in same view/page. Destroy method in col-md-8with foreach loop while store method in col-md-4
Its quite obvious, that your form don't have a unique name or id, so that's why the second method is redirected to destroy method. Do something like this:
cex-store-1
cex-destroy-1

How to show Record by input CNIC Number in laravel

conroller
public function search()
{
$search=\Request::get('search');
$needy=needAuth::where('cnic','like','%'.$search.'%')->orderBy('id')->paginate(30);
return view('needyStatus', compact('needy'));
}
View
{!! Form::open(['method'=>'GET','url'=>'needyStatus','class'=>'navbar-form navbar-left','role'=>'search'])!!}
<div class="input-group custom-search-form">
<input type="text" name="search" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-default-sm">
<i class="fa fa-search"></i>
</button>
</span>
</div>
{!! Form::close() !!}
</div>
<tr>
<hidden>
#foreach($needy as $ned)
{{$ned->cnic}}
{{$ned->email}}
'{{$ned->firstName}}
#endforeach
</hidden>
</tr>
i enter CNIC it shows but when i refresh page is shows all data without enter any cnic number. how to hide data and only show by enter cnic number which show record?
Give the condition here:
public function search(){
$search=\Request::get('search');
if(isset($search)){
$needy=needAuth::where('cnic','like','%'.$search.'%')->orderBy('id')->paginate(30);
}
return view('needyStatus', compact('needy'));
}

Laravel form mime type validation

Form is file uploader. Laravel doesnt give me error if validation fails on mime type. If it fails on input required it gives me error on my upload page properly. It looks like validation is right but it only doesnt give me back error if mime type is wrong, because it doesnt upload file if file is wrong.
route
Route::post('/newfile', function (Request $request) {
$validator = Validator::make($request->all(), [
'userFile' => 'required|mimes:zip',
]);
if ($validator->fails()) {
return redirect('/upload')
->withErrors($validator);
} else {
view
#include('errors.errors')
<form action="{{ url('newfile') }}" method="POST" id="uploadForm" class="form-horizontal" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-primary btn-file">
Browse… <input name="userFile" id="userFile" type="file" />
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<div>
<button type="submit" id="btnSubmit" value="Submit" class="btn btn-success">Upload</button>
<div class="progress">
</div>
</div>
</form>
error
#if (count($errors) > 0)
<!-- Form Error List -->
<div class="alert alert-danger">
<strong>Whoops! Something went wrong!</strong>
<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Fixed, my javascript code for upload blocked errors from validator.

User Edit Resource not working

I have a user resource with is linked in the users table.
My Route:
Route::resource('user', 'UserController');
UserController.php
public function edit($id)
{
$user = User::find($id);
return view('user.edit')->with(array('user'=>$user));
}
public function update(Request $request, $id)
{
$rules = array(
'name' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('user/'.$id.'/edit')->withInput()->withErrors($validator);
}
}
And my View
{!! Form::model($user, array('route' => array('user.update', $user->id), 'method' => 'PUT', 'class' => 'form-horizontal')) !!}
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }}</p>
#endif
#endforeach
</div>
<div class="form-group"><label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10"><input type="text" name="name" id="name" value="{{$user->name}}" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">ID Number</label>
<div class="col-sm-10"><input type="text" name="id_number" id="id_number" value="{{$user->id_number}}" class="form-control"></div>
</div>
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Save changes</button>
</div>
</div>
{!! Form::close() !!}
So with this setup I expect that when click the submit button on my page it will go in the update() function just like my other resource. But problem is when I click submit it will direct me to
http://localhost/hrs/public/user/1
and a white blank page with no errors what so ever. So it means it's going to my update function? I am following same pattern with my other resource and this is the only one not working.
You have wrong web server configuration. You should point your web server (usually Apache or nginx) to a public directory of your Laravel project. After that restart web server.
For example for Apache correct configuration will be something like this:
DocumentRoot "C:/xampp/htdocs/hrs/public"
<Directory "C:/xampp/htdocs/hrs/public">
Found the problem, I don't have the else part of the validation. as that is where the event goes to. Since I don't have it, it will do nothing.
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('user/'.$id.'/edit')->withInput()->withErrors($validator);
}
else
{
dd($rules);
}

CRUD Laravel 5 how to link to destroy of Resource Controller?

I have a link
<a class="trashButton" href="{{ URL::route('user.destroy',$members['id'][$i]) }}" style="cursor: pointer;"><i class="fa fa-trash-o"></i></a>
this link is supposed to direct to the destroy method of the Usercontroller , this is my route Route::resource('/user', 'BackEnd\UsersController');
UserController is a Resource Controller. But at this moment it is directing me to the show method rather than directing to the destroy method
You need to send a DELETE request instead of a GET request. You can't do that with a link, so you have to use an AJAX request or a form.
Here is the generic form method:
<form action="{{ URL::route('user.destroy', $members['id'][$i]) }}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button>Delete User</button>
</form>
If you're using Laravel 5.1 or later then you can use Laravel's built-in helpers to shorten your code:
<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button>Delete User</button>
</form>
If you're using Laravel 5.6 or later then you can use the new Blade directives to shorten your code even further:
<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">
#method('DELETE')
#csrf
<button>Delete User</button>
</form>
You can read more about method spoofing in Laravel here.
This is because you are requesting the resources via GET method instead DELETE method. Look:
DELETE /photo/{photo} destroy photo.destroy
GET /photo/{photo} show photo.show
Both routes have the same URL, but the header verb identifies which to call. Looks the RESTful table. For example, via ajax you can send a DELETE request:
$.ajax({
url: '/user/4',
type: 'DELETE', // user.destroy
success: function(result) {
// Do something with the result
}
});
I use this template 'resources/views/utils/delete.blade.php'
<form action="{{ $url or Request::url() }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type='submit' class="{{ $class or 'btn btn-danger' }}" value="{{ $value or 'delete' }}">{!! $text or 'delete' !!}</button>
</form>
Called as this:
#include('utils.delete',array( 'url' => URL::route('user.destroy',$id),'text' => '<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> delete me'))
If you're looking to do this via a regular link instead of through AJAX or another type of form request you can set up a special route that will respond to a normal GET request:
In your routes, define this in addition to the resource:
Route::get('user/{site}/delete', ['as' => 'user.delete', 'uses' => 'UserController#destroy']);
In your view:
Delete this user
In your controller:
public function destroy(User $user)
{
$user->delete();
return redirect()->route('users.index');
}
If we need to use an anchor to trigger the destroy route, and we don't want to use ajax, we can put a form inside our link, and submit the form using the onclick attribute:
<a href="javascript:void(0);" onclick="$(this).find('form').submit();" >
<form action="{{ url('/resource/to/delete') }}" method="post">
<input type="hidden" name="_method" value="DELETE">
</form>
</a>
If you really want to visit the destroy action on delete route by HTML, then there is an approach to use HTTP Method Spoofing which means that you could visit a delete HTTP method by adding a hidden input named _method with the value of `"DELETE". Same way can be used for "PUT" and "PATCH" HTTP method.
Below is a sample for DELETE method.
<form action="/tasks/5" method="POST">
<input type="hidden" name="_method" value="DELETE">
</form>
will get the route
DELETE /tasks/{id} destroy tasks.destroy
if you use laravel collective, you can write this way in your views.
{!! Form::open(['url' => '/tasks/'.$cat->id, 'method' => 'delete']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
In case someone came here to find how to replace standard laravel form for delete, from button in it to link, you can just replace:
{!! Form::open(['method' => 'DELETE', 'route' => ['tasks.destroy', $task->id],'onsubmit' => 'return confirm("Are you sure?")', 'id'=>'himan']) !!}
{!! Form::submit('Delete') !!}
{!! Form::close() !!}
TO
{!! Form::open(['method' => 'DELETE', 'route' => ['tasks.destroy', $task->id],'onsubmit' => 'return confirm("Are you sure?")', 'id'=>'himan']) !!}
Delete
{!! Form::close() !!}
Just replace button with simple <a href="#"... but with onclick attribute to submit the form!
If you want to use a link, you can use a library I have created that lets people make links that behave like POST, DELETE... calls.
https://github.com/Patroklo/improved-links
GET and DELETE Both routes have the same URL, but the header verb identifies which to call.
Here are my code snippets for edit and delete. I use bootstrap modal confirmation for delete action
<div class="btn-group">
<a href="{{ route('locations.edit', $location->id) }}"
class="btn btn-default btn-sm">
<i class="fa fa-pencil"></i>
</a>
<span class="btn btn-danger btn-sm formConfirm"
data-form="#frmDelete-{{$location->id}}"
data-title="Delete Location"
data-message="Are you sure you want to delete this Location ?">
<i class="fa fa-times"></i>
</span>
<form method="POST"
style="display: none"
id="frmDelete-{{$location->id}}"
action="{{ route('locations.destroy' , $location->id) }}">
{!! csrf_field() !!}
{{ method_field('DELETE') }}
<input type="submit">
</form>
BootStrap Modal
<div class="modal fade" id="formConfirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span
class="sr-only">Close</span></button>
<h4 class="modal-title" id="frm_title">Delete</h4>
</div>
<div class="modal-body" id="frm_body"></div>
<div class="modal-footer">
<button style='margin-left:10px;' type="button" class="btn btn-primary col-sm-2 pull-right"
id="frm_submit">Yes
</button>
<button type="button" class="btn btn-danger col-sm-2 pull-right" data-dismiss="modal" id="frm_cancel">
No
</button>
</div>
</div>
</div>
And Finally JS code
$('.formConfirm').on('click', function (e) {
e.preventDefault();
var el = $(this);
var title = el.attr('data-title');
var msg = el.attr('data-message');
var dataForm = el.attr('data-form');
$('#formConfirm')
.find('#frm_body').html(msg)
.end().find('#frm_title').html(title)
.end().modal('show');
$('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
});
$('#formConfirm').on('click', '#frm_submit', function (e) {
var id = $(this).attr('data-form');
$(id).submit();
});
My, non-ajax version. I use it in dropdowns (bootstrap) in resource list (datatables as well). Very short and universal.
Global jQuery method:
$('.submit-previous-form').click(function (e) {
e.preventDefault();
$($(this)).prev('form').submit();
});
And then we can use everywhere something like this:
{{ Form::open(['route' => ['user.destroy', $user], 'method' => 'delete']) }} {{ Form::close() }}
<i class="icon-trash"></i> Delete him
Recommend: It's easy to integrate with confirms scripts for example swal.
you can try this: (you can pass your id)
<form action="{{ route('tasks.destroy', $dummy->id) }}" method="post">
#csrf
#method('DELETE')
<a href="#" class="btn btn-danger" title="Delete" data-toggle="tooltip" onclick="this.closest('form').submit();return false;">
<i class="bi bi-trash-fill" style="color:white"></i>
</a>
</form>
requires route like:
Route::get('/tasks/delete/{id}', 'TasksController#destroy')
->name('tasks.destroy');
your controller:
public function destroy($id)
{
$task = Task::find($id);
$task->delete();
return redirect('/home')->with('success','Task Deleted Successfully');
}
or you can try this
{!! Form::open(['method' => 'DELETE','route' => ['reports.destroy', $dummy->id],'class'=>'']) !!}
{{ Form::button('<i class="bi bi-trash-fill" style="color:white"></i>', ['type' => 'submit', 'class' => 'delete get-started-btn-two'] ) }}
{!! Form::close() !!}

Categories