Laravel - search submit is not redirecting to the next blade - laravel

In my Laravel-5.8, I am using the index as the search page:
public function index()
{
$search = '';
if (request('search'))
{
$search = request('search');
return redirect()->route('client', [$search]);
}
return view('index', ['search' => $search]);
}
public function client($clientid)
{
$myparam = $clientid;
$client = new Client();
$res = $client->request('GET','https://example/{$myparam}', [
'query' => ['key' => 'jkkffd091']
])->getBody();
$geoLocation = json_decode($res->getContents(), true);
return view('client', [
'geoLocation' => $geoLocation
]);
}
Here is my index blade:
<form method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
I have this route:
Route::get('/', [HomeController::class, 'index'])->name('index');
Route::get('client/{search}', [HomeController::class, 'client'])->name('client');
What I want to achieve is that when the search button for index is submitted with the clientid in the text input field, it should take the clientid as parameter and pass it to client controller. Also redirect to client blade.Then when nothing is in the text input field, it should indicate.
But it is not redirecting. How do I achieve this?
Thanks

Probably you want to submit without a submit button. Then you can submit with JS :
<form id="submitForm" method="GET" action="{{ route('index', ['search' => $search]) }}">
<div class="field">
<label class="label blog-sidebar-label" for="search">
<input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
</label>
</div>
</form>
<!-- JS code below -->
<script>
document.getElementById("search").onchange = function() {myFunction()};
function myFunction() {
document.getElementById("submitForm").submit();
}
</script>

Related

Get product id to store attachments accordingly

I currently have the add attachment button for each product on the product list page. After clicking the button, will proceed to add attachment form. How do I get the current product ID from the product table in order to store the attachment data into the attachment table?
Route
Route::post('/store/{product}', 'AttachmentController#store')->name('attachment.store');
Product Model
public function attachment()
{
return $this->hasMany(Attachment::class, 'product_id', 'id');
}
Attachment Model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Controller
public function create()
{
return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {
$data['product_id'] = $product->id;
$data = $request->validate([
'file' => 'required',
'file.*' => 'mimes:csv,xlsx,pdf,docx',
]);
$attachmentData = [];
if($request->hasFile('file'))
{
foreach($request->file('file') as $file) {
$path = public_path('storage/attachments/'.$request->product_id);
$fileName = time().'-'.$file->getClientOriginalName();
$file->move($path, $fileName);
$attachmentData[] = $fileName;
}
$data['file'] = json_encode($attachmentData);
}
$attachment = Attachment::create($data);
return redirect()->route('product.index')->with('success','Attachment added successfully');
}
Blade View
<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
#csrf
<h3><b>Add Attachment</b></h3>
<input type="submit" class="btn btn-primary mr-2" value="Save">
<div class="row">
<h4 class="card-title">General</h4>
<input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Attachment </label>
<div class="input-group-append">
<label for="attachment" class="btn btn-info">Upload</label>
<input id="attachment" type="file" name="file[]" multiple required>
</div>
</div>
</div>
</form>
You have to use form action like below
<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

Ajax script to update record does not work, Laravel

I wrote a small script that updates the information on the page when editing. Everything basically works as it should, but I just can’t update the image. I don’t understand what the matter is. Without a script, with a page reload, everything works as it should.
Ajax script
<script type="text/javascript">
$("document").ready(function() {
$("#editPostButton{{$post->id}}").click(function() {
var formData = $("#EditPostForm{{$post->id}}").serialize();
$.ajax({
url: "{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}",
type: "POST",
data: formData,
success: function(data) {
$("#textpostdata{{$post->id}}").html($(data).find("#textpostdata{{$post->id}}").html());
$("#closeButton{{$post->id}}").click();
}
});
});
});
</script>
My Controller
public function editPost(Request $request, $id, $postId) {
$validator = $this->validate($request,[
'title' => 'max:100',
'message' => 'max:5000',
'img' => 'mimes:jpeg,png,gif,jpg|max:5000',
'videoPost' => 'max:100'
]);
if($validator) {
$user = User::find($id);
if(!$user && $user != Auth::user()->id) {
return abort(404);
}
$post = Profile::find($postId);
if(!$post) {
return abort(404);
}
$post->user_id = Auth::user()->id;
$post->title = $request->title;
$post->message = $request->message;
$post->videoPost = str_replace('watch?v=', 'embed/', $request->videoPost);
if($request->file('img')) {
$path = Storage::putFile('public/'.Auth::user()->id.'/post', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->update();
return redirect()->back();
}
}
And update form
<form action="{{route('editPost', ['id' => $user->id, 'postId' => $post->id])}}" method="post" enctype="multipart/form-data" id="EditPostForm{{$post->id}}" name="postForm">
#csrf #method('PATCH')
<div class="form-group">
<textarea maxlength="100" name="title" class="form-control" rows="1">{{$post->title}}</textarea>
</div>
<div class="form-group">
<textarea id="message" maxlength="5000" name="message" class="form-control" rows="10">{{$post->message}}</textarea>
</div>
<div class="form-group">
<textarea maxlength="100" class="form-control mt-1" id="videoPost" name="videoPost" cols="100" rows="1">{{$post->videoPost}}</textarea>
</div>
<h6>Current image</h6>
<img src="{{$post->img}}" class="img-fluid mb-2" width="230">
<div class="form-group">
<input type="file" id="img" name="img" accept="image/*">
</div>
<button type="button" class="btn btn-sm btn-primary" id="editPostButton{{$post->id}}">Edit</button>
</form>

I want to send email for more than one user to Mailtrap

I tried to send an email to a user and arrived at Miltrap
Now I put all the users on my system (table users in database) and introduced them to checkboxs and I want to send one email to more than one user or to all users and I did not see the result on the mailtrap
This is the code
MailboxController.php
public function form(Request $request)
{
$users = User::where('id', '!=', auth()->user()->id)->get();
return view('MailBox.form',compact('users'));
}
public function contact(Request $request)
{
//$emails = [];
$this->validate($request, [
'email' => 'required|email',
'subject' => 'min:3',
'message' => 'min:10']);
$data = array(
'email' => $request->email,
'subject' => $request->subject,
'bodyMessage' => $request->message
);
Mail::send('MailBox.contact', $data, function($message) use ($data){
$message->from('info#dev-any.com');
$message->to($data['email']);
$message->subject($data['subject']);
});
Session::flash('success', 'Your Email was Sent!');
return redirect('/dashboard/mailbox');
}
Web.php
Route::get('/mailbox', 'MailboxController#form')->name('mailbox.form');
Route::post('/mailbox/contact', 'MailboxController#contact')->name('contact');
form.blade.php
<form action="{{ route('contact') }}" method="POST">
{{ csrf_field() }}
<div class='form-group col-md-6'><strong>Select User :</strong><br>
<input type="checkbox" id = "chckHead" name="chk_all" value="" onchange="checkall()" id='allcb' /><strong> Check All </strong> </br>
#foreach ($users as $user)
<tr>
<td><input type="checkbox" class = "chcktbl" onchange="check()" name="email" id="email" value={{ $user->id }}></td>
<td>{{ $user->name }}</td></br>
</tr>
#endforeach
</div>
<div class="form-group col-md-6">
<label name="subject">Subject:</label>
<input id="subject" name="subject" class="form-control">
</div>
<div class="form-group col-md-6">
<label name="message">Message:</label>
<textarea id="message" name="message" class="form-control">Type your message here...</textarea>
</div>
<input type="submit" value="Send Message" class="btn btn-success col-md-6">
</form>
</div>
</div>
<script type="text/javascript">
$('.chcktbl').click(function () {
var length = $('.chcktbl:checked').length;
if (length > 3) {
// alert(length);
$('.chcktbl:not(:checked)').attr('enable', true);
}
else {
$('.chcktbl:not(:checked)').attr('enable', false);
}
});
</script>
<script type="text/javascript">
$('#chckHead').click(function () {
if (this.checked == false) {
$('.chcktbl:checked').attr('checked', false);
}
else {
$('.chcktbl:not(:checked)').attr('checked', true);
}
});
$('#chckHead').click(function () {
});
Simply change the email checkbox, and modify the validation
<input type="checkbox" class="chcktbl" onchange="check()" name="email[]" id="email" value={{ $user->id }}>

Laravel 5 how to use get parameter from url with controller's sign in method

I'm trying to implement a login system where the user will be redirect back only if there is a get parameter in the url, else it will be redirect to the profile page.
So, if the uri is something like this (no get parameter)
/login
if success, the user will be redirect to the profile page.
But if the uri has the get parameter like for example
/login?r=articles
the user will be redirected to the articles page instead of the default route to the profile page.
Question is, in the controller, how can do this, if possible, or how can I check for the get parameter?
routes.php
// Signin
Route::post('/account/signin', [
'uses' => 'UserController#postSignIn',
'as' => 'user.signin',
]);
UserController.php
// Signin
public function postSignIn(Request $request)
{
$this->validate($request, [
'login-email' => 'required|email',
'login-password' => 'required'
]);
if ( Auth::attempt(['email' => $request['login-email'], 'password' => $request['login-password']]) )
{
// Tried this, isn't working... (maybe something's missing ??)
$redirect = $request->input('r');
if ($redirect) {
return redirect()->route($redirect);
}
// -->
return redirect()->route('user.account');
}
return redirect()->back();
}
signin.blade.php
<form role="form" action="{{ route('user.signin') }}" method="post" class="login-form" name="login">
<div class="form-group {{ $errors->has('login-email') ? 'has-error' : '' }}">
<label class="sr-only" for="email">Email</label>
<input type="text" name="login-email" value="{{ Request::old('login-email') }}" placeholder="Email..." class="form-username form-control" id="form-username">
</div>
<div class="form-group {{ $errors->has('login-password') ? 'has-error' : '' }}">
<label class="sr-only" for="password">Password</label>
<input type="password" name="login-password" value="{{ Request::old('login-password') }}" placeholder="Password..." class="form-password form-control" id="form-password">
</div>
<div class="form-group">
<input type="checkbox" name="remember" value="{{ Request::old('remember') }}" id="remember">
Remember
</div>
<button type="submit" class="btn">Sign in!</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
Thanks.
Updated
Thank you all for your replies, the fact is that I'm still getting to know Laravel and that's probably why I can't implement it right the solutions that you guys shared.
So this said, I got it working by creating a conditional hidden field that holds the query value and this way once the user submits the form, it will be passed with the rest of the $response arguments.
signin.blade.php
<form role="form" action="{{ route('user.signin') }}" method="post" class="login-form" name="login">
<div class="form-group {{ $errors->has('login-email') ? 'has-error' : '' }}">
<label class="sr-only" for="email">Email</label>
<input type="text" name="login-email" value="{{ Request::old('login-email') }}" placeholder="Email..." class="form-username form-control" id="form-username">
</div>
<div class="form-group {{ $errors->has('login-password') ? 'has-error' : '' }}">
<label class="sr-only" for="password">Password</label>
<input type="password" name="login-password" value="{{ Request::old('login-password') }}" placeholder="Password..." class="form-password form-control" id="form-password">
</div>
<div class="form-group">
<input type="checkbox" name="remember" value="{{ Request::old('remember') }}" id="remember">
Remember
</div>
<button type="submit" class="btn">Sign in!</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
<!-- Verify condition -->
#if(isset($_GET['referer']))
<input type="hidden" name="referer" value="{{ $_GET['referer'] }}">
#endif
</form>
UserController.php
// Signin
public function postSignIn(Request $request)
{
$this->validate($request, [
'login-email' => 'required|email',
'login-password' => 'required'
]);
if ( Auth::attempt(['email' => $request['login-email'], 'password' => $request['login-password']]) )
{
// Check for the new argument 'referer'
if (isset($request->referer)) {
return redirect()->route($request->referer);
}
// -->
return redirect()->route('user.account');
}
return redirect()->back();
}
Like so, it works.
Don't know if it's a viable and secure way to do it in Laravel 5, but it is working.
When you have an URI such as login?r=articles, you can retrieve articles like this:
request()->r
You can also use request()->has('r') to determine if it's present in the URI.
And request()->filled('r') to find out if it's present in the URI and its value is not empty.
// only query
$query_array = $request->query();
or
$query = $request->query('r');
// Without Query String...
$url = $request->url();
// With Query String...
$url = $request->fullUrl();
If you are using Laravel then use their helper which works just out of the box, i.e. if your route or url has a auth middlewere and user is not logged in then it goes to login and in your postSign or inside attempt just
return redirect()->intended('home'); //home is the fallback if no intended url is provide
UserController
public function postSignIn(Request $request){
$this->validate($request, [
'login-email' => 'required|email',
'login-password' => 'required'
]);
if ( Auth::attempt(['email' => $request['login-email'], 'password' => $request['login-password']]) )
{
return redirect()->intended('user.account);
}
return redirect()->back();
}
first use this
use Illuminate\Support\Facades\Input;
then you can get any data from your url
$name=Input::get('term', false); //term is the parameter name we get from URL
If you are still in this quest you can use
Request
like
$request->r

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Resources