Laravel 5 - How to send url paramaters in form - laravel

I have a form with some input in a search page who has an URL with many parameters and I want to send them in this form or any other way .
Form code
{!! Form::open(['route' => ['test.mail'],'method' => 'post','files' => true]) !!}
{!! Form::token() !!}
<div class="box-header">
<i class="fa fa-envelope"></i>
<h3 class="box-title">Quick Email</h3>
<!-- tools box -->
<div class="pull-right box-tools">
<!--<button class="btn btn-info btn-sm" data-widget="remove" data-toggle="tooltip" title="Remove"><i class="fa fa-times"></i></button>-->
</div><!-- /. tools -->
</div>
<div class="box-body">
<div class="form-group">
<input type="text" class="form-control" name="object" placeholder="Subject" />
</div>
<div class="form-group">
<textarea class="textarea" name="textu" placeholder="Message" cols="120" rows="8"></textarea>
</div>
<div class="form-group">
<input type="file" class="form-control" name="filee" />
</div>
</div>
<div class="box-footer clearfix">
<input type="submit" name="sendEmail" class="pull-right btn btn-default" id="sendEmail" value="Send">
</div>
{!! Form::close() !!}

This is how you get all the values in your url
foreach($_GET as $key=>$value){
echo $key, ' => ', $value, "<br/>n";
}
then to send them in your form you simply create an input type hidden like this:
<input id="someId" name="UrlValue" type="hidden" value="$UrlValue">

I hope this will help,
// Get the current URL without the query string...
echo url()->current();
// Get the current URL including the query string...
echo url()->full();
// Get the full URL for the previous request...
echo url()->previous();
Each of these methods may also be accessed via the URL facade:
use Illuminate\Support\Facades\URL;
echo URL::current();
https://laravel.com/docs/5.6/urls

Related

Laravel 8 - All validation rules are shown if one rule applies

I am using Laravel Framework 8.62.0 and I am having the following validation rules:
$rules=[
'username' => 'required|min:3|max:30|alpha_dash',
'email' => "required|email|unique:users,email",
'password' => 'required|min:6|confirmed',
];
$error_messages=[
'username.required'=>'The username-field is required.',
'username.min'=>'Your username must be longer than 3 characters.',
'username.max'=>'Please shorten your username.',
'username.alpha_dash'=>'Please use letters from A-Z and a-z, dashes (-) or underscores(_).',
'email.unique'=>'Your email is already used.',
'email.email'=>'Please add a correct email-address.',
'email.required'=>'The email-field is required.',
'password.required'=>'The password-field is required.',
'password.min'=>'Your password must have at least 6 characters.',
'password.confirmed'=>'Your entered passwords do not match.',
];
$validator = validator($request->all(), $rules, $error_messages);
My form looks like the following:
<form id="Register" class="card-body" tabindex="500" action="{{ url('register') }}" method="POST">
<!-- CSRF Token -->
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<div class="name">
<input type="text" name="username" value="{!! old('username') !!}">
<label>Username</label>
<li>
{!! $errors->first('username.required', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
{!! $errors->first('username.min', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
{!! $errors->first('username.max', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
{!! $errors->first('username.alpha_dash', '<ul><span style="color: red;" class="help-block">:message</span></ul>') !!}
</li>
</div>
<div class="mail">
<input type="email" name="email" value="{{ old('email') }}">
<label>Mail</label>
{!! $errors->first('email.unique', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('email.required', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('email.email', '<span style="color: red;" class="help-block">:message</span>') !!}
</div>
<div class="passwd">
<input type="password" name="password" value="{{ old('password') }}">
<label>Password</label>
{!! $errors->first('password.min', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('password.confirmed', '<span style="color: red;" class="help-block">:message</span>') !!}
{!! $errors->first('password.required', '<span style="color: red;" class="help-block">:message</span>') !!}
</div>
<div class="passwd">
<input type="password" name="password_confirmation" value="{{ old('password_confirmation') }}">
<label>Confirm Password</label>
{!! $errors->first('password.confirmed', '<span style="color: red;" class="help-block">:message</span>') !!}
</div>
<div class="submit">
<!-- <a class="btn ripple btn-primary btn-block" href="#">Register</a> -->
<input type="submit" class="btn ripple btn-primary btn-block" value="Register">
</div>
<p class="text-dark mb-0">Already have an account?Sign In</p>
</form>
When I enter a username with 3 characters and without a - and my password lengths do not match I get all validation errors back:
However, I would only like to get the errors back that really apply.
Any suggestions what I am doing wrong?
I appreciate your replies!
You are asking the blade file to display every error that you have created by name/key, rather than seeing what's inside the error bag.
Laravel automatically presents the errors that apply to your page, and limits the output to only those that apply. You don't need to catch them individually by name as you have with $errors->first('email.unique')... etc.
Take a look at the docs on how to display validation errors, it's pretty nifty. Basically check the error bag and if they are presented, display only those that are in the bag:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
The $errors variable is available to you on any view within a route under the web middleware.

Laravel 5.5 redirect to url with anchor and with data

In my footer.blade.php i have the following code about subscribing
<!--Subscription-->
#if(Session::has('success'))
<div class="form-group has-success">
<input class="form-control form-control-success" type="text" id="input-success">
<div class="form-control-feedback">{{ Session::get('success') }}</div>
</div>
#elseif(Session::has('failed'))
<div class="form-group has-danger">
<input class="form-control form-control-danger" type="text" id="input-danger">
<div class="form-control-feedback">{{ Session::get('failed') }}</div>
</div>
#else
{!! Form::open(['route'=>'subscribe.store', 'class' => 'subscribe-form', 'novalidate' => 'novalidate']) !!}
<div class="clearfix">
<div class="input-group input-light">
{!! Form::email('email', old('email'), ['class'=>'form-control ', 'placeholder'=>'Your e-mail']) !!}
<span class="input-group-addon"><i class="icon-mail"></i></span>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input type="text" name="b_c7103e2c981361a6639545bd5_1194bb7544" tabindex="-1">
</div>
<button class="btn btn-primary" type="submit">
<i class="icon-check"></i>
</button>
</div>
{!! Form::close() !!}
<span class="form-text text-sm text-white opacity-50">Subscribe to our Newsletter to receive early discount offers, latest news, sales and promo information.</span>
#endif
In my controller i have the following function which receives the email and subscribes it correctly
public function registerNewsletter( Request $request )
{
$email = $request->input( 'email' );
$isSub = Newsletter::hasMember($email);
if($isSub) {
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.');
} else {
Newsletter::subscribe($email);
return redirect()->back()->with('success', 'You have been registered in our Newsletter system.');
}
}
Although everything works good, i would like to page to scroll down to the footer because now it reloads and stays on top.
I've found the return redirect()->to(app('url')->previous(). '#hashid');
But there is no way to pass data among the id of the footer.
And also i've tried
return redirect()->back()->with('failed', 'You have been already registered in our Newsletter system.'). '#sitefooter';
and it didn't scroll down.
Any idea or workaround?
I've just tested this code. It will redirect you, scroll down to the anchor and will pass the data:
session()->flash('someVariable', $someData);
return redirect(url()->previous() . '#hashid');
To get stored data:
$someData = session('someVariable');
Or in a view:
{{ session('someVariable') }}

Strange view error on Laravel

I have some cotroller like this:
Route::get('/article/create', 'ArticlesController#create');
and here's my ArticlesController#create:
public function create(){
return view('articles.create',
[
'title'=>'Add Artikel',
'username'=>'Whatever Myname',
'status' => 'Offline'
]
);
}
when i trying to access blog.dev/article/create i got this strange errors:
"Trying to get property of non-object (View: E:\xampp\htdocs\blog\resources\views\articles\single.blade.php)"
how come i can get this kind of error when my view is pointing at articles.create but the error is at single.blade.php which it suppose for ArticlesController#view?
this is what in create.blade.php:
#extends('admin.layout')
#section('content')
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Horizontal Form</h3>
</div>
#include('admin.formerrors')
<form method="post" class="form-horizontal" action="/articles">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input class="form-control" id="title" name="title" placeholder="Judul Artikel">
</div>
</div>
<div class="form-group">
<label for="content" class="col-sm-2 control-label">Content</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="content" name="content"></textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
#endsection
and here's in my single.blade.php :
#extends('admin.layout')
#section('content')
<h1>{{ $article->title }}</h1>
<p>{{ $article->content }}</p>
<hr>
#foreach($article->comments as $comment)
<blockquote>
<p>{{ $comment->comment }}</p>
<small>{{ $comment->created_at->diffForHumans() }}</small>
</blockquote>
#endforeach
#include('admin.formerrors')
<form method="post" class="form-horizontal" action="/article/{{ $article->id }}/comment">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="comment" class="col-sm-2 control-label">Comment</label>
<div class="col-sm-10">
<textarea class="form-control" rows="3" id="comment" name="comment"></textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
#endsection
and here's my router:
Route::get('/articles', 'ArticlesController#index')->name('home');
Route::post('/articles', 'ArticlesController#save');
Route::get('/article/{id}', 'ArticlesController#view');
Route::get('/article/create', 'ArticlesController#create');
Route::post('/article/{article}/comment', 'CommentsController#save');
Route::get('/register', 'RegistrationController#create');
Route::post('/register', 'RegistrationController#store');
I try to change the create function by pointing into another view, but still it showing same error and pointing at single.blade view.
I delete all code at single.blade and write 'test' text, i don't get any errors. but i'm pointing my controller for viewing into create.blade not sigle.blade
After seeing you routes the problem is in this two routes :
Route::get('/article/{id}', 'ArticlesController#view');
Route::get('/article/create', 'ArticlesController#create');
In this case Laravel will consider the create in your path blog.dev/article/create as an id parameter of the view route here => /article/{id}.
So as a solution you should simply inverse the two routes :
Route::get('/article/create', 'ArticlesController#create');
Route::get('/article/{id}', 'ArticlesController#view');
You need to find what's in the file by reading more than just that line. Maybe you're including that file in the articles.create? Maybe you're accessing a variable that doesn't exist whenever you load the page. Edit your answer with more of the error and what's inside both blades and we can pinpoint what's wrong.

want to pass the post value in to controller

Here am having the code like this
<div class="form-group">
<label class="col-lg-3 control-label">Start Date</label>
<div class="col-lg-5">
<div class="input-group">
<input type="text" required name="attendance_date" id="attendance_date" class="form-control datepicker" value="<?php echo date('Y-m-d');?>" data-date-format="<?= config_item('date_picker_format'); ?>" required>
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
</div>
</div>
</div>
<a data-toggle="modal" data-target="#myModal" type="button" name="update" href="<?php echo base_url();?>admin/attendance_confirmation/reject1/<?php echo $this->input->post('attendance_date');?>" id="update1" value="Reject" class="btn btn-danger ml" ><i class="fa fa-times"></i> <?= lang('reject') ?></a>
and my controller looks like this
public function reject1($date)
{
$data['date']=$date;
var_dump($data['date']);
$data['modal_subview'] = $this->load->view('admin/engineer_attendance_confirmation/attendance_confirmation_modal',$data,FALSE);
$this->load->view('admin/_layout_modal', $data);
}
but the value in the attendance_date is not getting in controller.how can we pass the value in the post to the controller using href tag
In CodeIgniter, POST data isn't passed through as variables into the controller function. You'd instead need to use the input library. You can then use $this->input->post() to get POST data:
$data['date'] = $this->input->post('attendance_date');
Using href tag you don't get data in the post, but you can get the data using a segment like this:
public function reject1()
{
$data['date']=$this->uri->segment(3);
var_dump($data['date']);
$data['modal_subview'] = $this->load->view('admin/engineer_attendance_confirmation/attendance_confirmation_modal',$data,FALSE);
$this->load->view('admin/_layout_modal', $data);
}

Multiple forms with same inputs name check which form input has error Laravel

I have something like this in my code:
#foreach($cars as $key => $car)
{!!Form::open(['action' => 'CarController#Update'])!!}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Color</label>
<div class="col-lg-6">
{!!Form::text('carColor', $car->color, ['class' => 'form-control input-sm'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Price</label>
<div class="col-lg-6">
{!!Form::text('carPrice', $car->price, ['class' => 'form-control input-sm'])!!}
</div>
</div>
</div>
{!!Form::close()}
#endforeach
The objective of this view is to update a car's price and color. But there are a lot so there's one form per car. In case the inputs don't pass the validation, how can I know which form inputs are the invalid since the inputs are named the same.
The problem is that the laravel has a session of old inputs but not for forms.
But this task is easy with javascript or jquery.
#foreach($cars as $key => $car)
{!!Form::open(['action' => 'CarController#Update'])!!}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Color</label>
<div class="col-lg-6">
{!!Form::text('carColor', $car->color, ['class' => 'form-control input-sm', 'id' => 'carColor'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Price</label>
<div class="col-lg-6">
{!!Form::text('carPrice', $car->price, ['class' => 'form-control input-sm', 'id'=> 'carPrice'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<input type="hidden" id="carID" value="{{ $car->id }}">
<button class="btn btn-warning" id="editDetails">edit</button>
</div>
</div>
{!!Form::close()}
#endforeach
and in your javascript
$('#editDetails').on('click', function () {
carColor = $(this).parent().parent().parent().find('#carColor').val();
carPrice = $(this).parent().parent().parent().find('#carPrice').val();
car_id = $(this).parent().parent().parent().find('#carID').val();
_token= $('meta[name="csrf-token"]').attr('content'); //add meta header in top head section see below
//here you can also check validation like check for empty fields
$.ajax({
url : 'url/to/edit/route',
method : 'patch', //this could be post. whatever you defined as your route
data : {
carColor : carColor,
carPrice : carPrice,
carId : carId,
_token : _token
},
success : function() {
alert('successful edit!');
//you can do something like
$(this).parent().parent().append('<p>success</p>');
//to show which line was successful
},
error : function(xhr,status,err) {
//you can do something like append an alert div to the parent form element of the erroneous input row.
$(this).parent().parent().append('<p>error editing here</p>');
}
});
});
add this meta tag with a csrf session as content in the head tag of your master layout
<meta name="csrf-token" content="{!! csrf_token() !!}">
Hope this would give you an idea on how you solve your problem.
EDIT
due to OP needing to handle this with no javascript
First add a hidden input of the key in foreach loop form to pass which row throws the error
<input type="hidden" id="key" value="{{ $key }}">
then in your controller you can add this to the error handling block
Session::flash('error', Input::get('key')); //use flash which behaves the same as as old input session
//a one time use session
and on inside the loop add an if statement checking for errors
#if(Session::has('error') || Session::get('error') == $key)
<div class="alert-box success">
<h2>error here</h2>
</div>
#endif
Hope this helps

Resources