Search Laravel Using Button - laravel

I want to search for data using a primary key, with PO as an example. Btw, I'm new to Laravel. Below is my code for my controller. I want to make the system go to the new page if the data that was searched exists(click on search button). If not, it will stay on the same page. Actually, I don't know whether my code is correct or not.
public function supplierindex(){
$supp_details = Supplier::where('PO','LIKE','%'.$searchPO.'%')->get();
return view ('frontend.praiBarcode.getweight')
->with('supp_details',$supp_details);
}
public function searchindex()
{
return view ('frontend.praiBarcode.getweight');
}
public function searchPO()
{
$searchPO = Supplier::where('PO','like',"%".$search."%")->get();
if (Supplier::where('PO','like',"%".$search."%")->exists()) {
return view('frontend.praiBarcode.getweight',compact('searchPO')); }
else {
return view('frontend.praiBarcode.index');
}
}
Below is my code in blade.php. However, the data does not come out on the screen.
<div class= "form-group">
#foreach ($supp_details as s)
<div style="font-size: 16px;" class="form-group row">
<label for="supp_name" class = "col-sm-2">PO</label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<label> {{ $s->PO }}</label>
</div>
</div>
#endforeach

In order to pass data into the view, you have to use the second argument of the view function.
Example:
public function supplierindex(){
$supp_details = Supplier::where('PO','LIKE','%'.$searchPO.'%')->get();
return view ('frontend.praiBarcode.getweight' ,['supp_details' => $supp_details]);
}

You can use count() to check if query result is empty or not
public function searchPO()
{
$searchPO = Supplier::where('PO','like',"%".$search."%")->get();
$countsearchPO = $searchPO->count();
if ($countsearchPO ) {
return view('frontend.praiBarcode.getweight',compact('searchPO')); }
else {
return view('frontend.praiBarcode.index');
}
}
And in your blade your variable is stored in session
$supp_details = Session::get('supp_details');
#foreach ($supp_details as s)
<div style="font-size: 16px;" class="form-group row">
<label for="supp_name" class = "col-sm-2">PO</label>
<label for="supp_name" class = "col-sm-1">:</label>
<div class="col-sm-7">
<label> {{ $s->PO }}</label>
</div>
</div>
#endforeach

Related

Passing form data from View Component to Controller in .NET Core MVC

I have a Component View and I try to update data from a form in it, I call the controller but in the controller I receive null :
public class CustomerPropertyViewComponent: ViewComponent
{
private MyDBContext context;
public CustomerPropertyViewComponent(MyDBContext _contex)
{
context = _contex;
}
public async Task<IViewComponentResult> InvokeAsync(int id)
{
CustomerPropertyModelView c = new CustomerPropertyModelView();
TblCustomerProperty t = new TblCustomerProperty(context);
c = t.getAllInfo(id);
if (c.model == null)
{
c.model = new TblCustomerProperty();
c.model.CustomerId = id;
}
return View(c);
}
}
and in the view I have
#model SunSystemDotNetCoreVersion.Models.helpers.CustomerPropertyModelView
<form asp-action="Update" asp-controller="CustomerProperties"
data-ajax="true"
data-ajax-method="POST"
method="post">
<div class="row w-100">
<div class="col-6">
<div class="row align-items-center h-100">
<div class="col-5 text-right">
Number of Bedrooms
</div>
<div class="col-7 p-1 p-1">
#Html.TextBoxFor(model => model.model.Bedrooms, new { #class = "form-control", Type = "number" })
</div>
<div class="col-5 text-right">
Current Heating System
</div>
<div class="col-7 p-1">
<select asp-for="model.HeatingSystemTypeId" class="form-control"
asp-items="#(new SelectList(Model.HeatingsList,"HeatingSystemTypeId","Title"))">
<option value="0">-Plaese Select-</option>
</select>
</div>
.....
<div class="col-12">
<button type="submit" >Save</button>
</div>
</div>
</form>
I have reduced most of the view code but it contains all data that the model needs. and this is my controller:
public class CustomerPropertiesController : Controller
{
private readonly MyDBContext_context;
public CustomerPropertiesController(MyDBContextcontext)
{
_context = context;
}
public IActionResult Update(TblCustomerProperty modelView) {
//here modelView is null
return View();
}
it should be work I don't know why it keeps sending null to my controller.
You could F12 to check the html elements in browser,and you will find the name of these elements are like:model.Bedrooms.Because your main model is CustomerPropertyModelView but your input belongs to TblCustomerProperty which named model in CustomerPropertyModelView.If your backend code recieve CustomerPropertyModelView as parameter,it will not be null.But if you recieve TblCustomerProperty as parameter,you need specify the suffix.
Change like below:
public IActionResult Update([Bind(Prefix ="model")]TblCustomerProperty modelView)
{
return View();
}

Eloquent update doesn't work in Laravel 6

I'm trying to update a field after submitting in the following form:
<form action="{{ route("comments.update") }}" method="post">
#csrf
<input type="hidden" name="commentIDToEdit" id="commentID">
<div class="md-form mb-5">
<i class="fas fa-comment"></i>
<label for="toEditComment"></label>
<textarea name="toEditCommentary" id="toEditComment" cols="3" rows="5" style="resize: none"
class="form-control"></textarea>
</div>
<div class="modal-footer d-flex justify-content-center">
<button type="submit" class="btn btn-default">Modificar</button>
</div>
</form>
I have the CommentsController, where I process the data from the form. Here is the code:
public function updateComment()
{
request()->validate([
"toEditCommentary" => "min:10|max:500"
]);
if (Session::has("username") && getWarningCount(User::whereUsername(session("username"))->value("email")) > 0) {
Caveat::where("commentID", request("commentIDtoEdit"))
->update(["updatedComment" => request("toEditCommentary")]);
} else {
die("No se cumple la condición");
}
if (Comment::where("commentID", request("commentIDToEdit"))->exists()) {
Comment::where("commentID", request("commentIDToEdit"))
->update(["commentary" => request("toEditCommentary")]);
}
return back();
}
Curiosly, the comment is updated in his table, but not the warning. I was thinking in the fillable property in the model, but I don't have it, instead this, I have the following code:
protected $guarded = [];
const UPDATED_AT = null;
const CREATED_AT = null;
Your hidden input is named commentIDToEdit, but in the Controller you fetch the Caveat using request("commentIDtoEdit") (different case).
What you wrote:
Caveat::where("commentID", request("commentIDtoEdit"))
What you should have done: (note the different casing)
Caveat::where("commentID", request("commentIDToEdit"))
This is because in the view, the input name is commentIDToEdit, not commentIDtoEdit.

Laravel Maatwebsite excel

I need your help. I don't know how to import the excel file. I mean I don't understand where to put this users.xlsx and how to get its directory
public function import()
{
Excel::import(new UsersImport, 'users.xlsx');
return redirect('/')->with('success', 'All good!');
}
its simple on mattwebsite you need a controller like below :
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
// note that these fields are completely different for you as your database fields and excel fields so replace them with your own database fields
$data['title'] = $row['title'];
$data['description'] = $row['description'];
$data['fax'] = $row['fax'];
$data['adrress1'] = $row['adrress1'];
$data['telephone1'] = $row['telephone1'];
$data['client_type'] = $row['client_type'];
if (!empty($data)) {
DB::table('clients')->insert($data);
}
}
});
}
Session::put('success on import');
return back();
}
and a view like this :
<form
action="{{ URL::to('admin/client/importExcel') }}" class="form-horizontal" method="post"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label col-lg-2">excel import</label>
<div class="col-lg-10">
<div class="uploader"><input type="file" name="import_file" class="file-styled"><span class="action btn btn-default legitRipple" style="user-select: none;">choose file</span></div>
</div>
</div>
<button class="btn btn-primary">submit</button>
</form>
and finally a route like below :
Route::post('admin/client/importExcel', 'ClientController#importExcel');

search with ajax laravel

I need my project to have a search form, I tried with this code, but when I execute console it says:
POST http://localhost:8000/buscar 500 (Internal Server Error)
then here is my view
<div id="qnimate" class="off">
<div id="search" class="open">
<button data-widget="remove" id="removeClass" class="closeSearch" type="button">×</button>
<input type="text" placeholder="Buscar Noticias - Articulos - Reviews" id="buscar" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
<button class="btn btn-lg btn-site" type="submit"><span class="glyphicon glyphicon-search"></span> Buscar</button>
<div id="resultadoBusqueda" class="col-md-12"></div>
</div>
</div>
here is my controller
public function buscar()
{
$keywords = Input::get('keywords');
$reviews = Reviews::where('estado','1')->take();
$buscarReviews = new \Illuminate\Database\Eloquent\Collection();
foreach ($reviews as $review) {
if(Str::contains(Str::lover($review->nombre), Str::lover($keywords)))
$buscarReviews->add($review);
}
return view::make('busqueda')->with('buscarReviews', $buscarReviews);
}
here is the view which shows the information
#foreach($buscarReviews as $review)
<div id="reviews" class="col-md-12">
<div class="col-md-4">
<img src="Imagenes/{{$review->logo}}" width="50">
</div>
<div class="col-md-8">
<h2>{{$review->nombre}}</h2>
<div>{!! str_limit($review->descripcion, $limit = 150, $end = '...') !!}</div>
</div>
</div>
#endforeach
here is my js
var timer;
function keydownFunction(){
timer = setTimeout(function(){
var keywords = $('#buscar').val();
if(keywords.length > 0){
$.post('/buscar', {keywords: keywords}, function(markup){
$('#resultadoBusqueda').html(markup);
});
}
}, 500);
}
function keyupFunction(){
clearTimeout(timer);
}
I don't know what is the reason that it doesn't print the information required.
you are sending post request from ajax but in your controller you are trying to get that value using get, try this code
public function buscar(Request $request)
{
$keywords = $request->keywords;
$reviews = Reviews::where('estado','1')->take();
$buscarReviews = new \Illuminate\Database\Eloquent\Collection();
foreach ($reviews as $review) {
if(Str::contains(Str::lover($review->nombre), Str::lover($keywords)))
$buscarReviews->add($review);
}
return view::make('busqueda')->with('buscarReviews', $buscarReviews);
}
also remember to change in route like this.
Route::post('buscar', 'yourController#buscar');

Laravel 4 - Many to Many - pivot table not updating

I get no obvious errors when adding a new job to my database.
My industry job goes into the jobs table but the relationship with divisions in my join table goes nowhere. I just can't see where I'm going wrong
JOIN TABLE
division_industryjob
division_id
industryjob_id
divisions
id
division_name
industryjobs
id
job_title
MODELS
Division.php
<?php
class Division extends \Eloquent {
protected $table = 'divisions';
/**
* Industry Jobs relationship
*/
public function industryjobs()
{
return $this->belongsToMany('IndustryJob');
}
}
IndustryJob.php
<?php
class IndustryJob extends \Eloquent {
protected $table = 'industryjobs';
public function divisions()
{
return $this->belongsToMany('Division');
}
}
ROUTES
Route::get('industry-jobs/add', 'AdminController#getCreateIndustryJob');
Route::post('industry-jobs/add', 'AdminController#postCreateIndustryJob')
CONTROLLER
// Create Industry - Get (empty form - new entry)
public function getCreateIndustryJob()
{
View::share('page_title', 'Create a new Industry Job Role');
View::share('sub_page_title', 'Ex: Mechanical Technician');
return View::make('admin/industry-jobs/create');
}
// Create Industry - Post
public function postCreateIndustryJob()
{
//validate user input
$rules = array(
'job_title' => 'Required|Min:3|Max:80'
);
$validation = Validator::make(Input::all(), $rules);
If ($validation->fails())
{
return Redirect::to('/admin/industry-jobs/add')->withErrors($validation);
} else {
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
if (isset($input['divisions'])) {
foreach ($input['divisions'] as $divId) {
$div = Division::find($divId);
$industryjob->divisions()->save($div);
}
}
$industryjob->save();
return Redirect::to('/admin/industry-jobs')->with('message', 'Industry Job created successfully');
}
}
FORM
<form class="form-horizontal" method="post" autocomplete="off">
<!-- Industry Job Title -->
<div class="form-group">
<label class="col-md-2 control-label" for="industry_name">Industry Job Title (*)</label>
<div class="col-md-10">
<input class="form-control" type="text" name="job_title" id="job_title" value="" />
</div>
</div>
<!-- ./ Industry Job Title -->
<!-- Industry Type -->
<div class="form-group">
<label class="col-md-2 control-label" for="body">Related Division</label>
<div class="col-md-10">
<select name="divisions[]" id="divisions" size="6" class="form-control" multiple>
#foreach (Division::all() as $division)
<option value="{{ $division->id }}" >{{ $division->division_name }}</option>
#endforeach
</select>
</div>
</div>
<!-- ./ Industry Type -->
<!-- Form Actions -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="reset" class="btn btn-default">Reset</button>
<button type="submit" class="btn btn-success">Create Job</button>
</div>
</div>
<!-- ./ form actions -->
</form>
You are saving the Parent model afterwards so it's not working. Save the Parent model before you save the Child Model, so it should be something like this:
$industryjob = new IndustryJob;
$industryjob->job_title = Input::get('job_title');
$industryjob->job_description = Input::get('job_description');
$industryjob->job_qualifications = Input::get('job_qualifications');
$industryjob->save();
Then save the related models using sync because it's many-to-many relationship and those related models are already created and available in the database:
if (isset($input['divisions'])) {
// Pass the array of ids to sync method
$industryjob->divisions()->sync($input['divisions']);
}
If you use the foreach loop then you may use something like this;
foreach ($input['divisions'] as $divId) {
$industryjob->divisions()->attach($divId);
}
Check more about inserting related models on Laravel website.

Resources