Can not get the value from input Livewire? - laravel

I have this form :
<div class="coupon d-flex align-items-center">
<input wire.model="coupon" type="text" class="input-text">
<button wire:click="applyCoupon" class="ml-3">#lang('site.apply_coupon')</button>
</div>
My Component:
class CouponCart extends Component
{
public $coupon;
public function applyCoupon(){
dd($this->coupon);
}
public function render()
{
return view('livewire.user.coupon-cart');
}
}
Why I always get null value when I click button ? even I fill the input!!

Because it's wire:model instead of wire.model.
You probably made a typo and added a . instead.

Related

Search Laravel Using Button

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

Refresh a job in livewire

I have two inputs in livewire view. When a value is entered in the first input, a calculation is performed in the component based on the data received from the api and the value in the first input, the result of which is displayed in the second input. Now I want that calculation to be done again every ten seconds and displayed in the second input. According to the livewire documentation, I used the poll, but only the view was refreshed and the new value was not displayed.I will put the codes below.
inputs :
<input wire:model="unit" type="text" class="form-control form-control-xl" style="text-align: center" value="0">
</br>
<input id="toman" type="text" style="text-align: center" class="form-control form-control-xl">
component:
<?php
namespace App\Http\Livewire\Frontend\Order;
use App\Models\Currency;
use App\Models\Network;
use Livewire\Component;
class Buy extends Component
{
public $currencySelect ='btc';
public $unit;
public function mount()
{
$this->unit = 0;
}
public function updatedUnit()
{
$this->validate([
'unit' => 'numeric',
]);
if ($this->unit !== ''){
$this->dispatchBrowserEvent('changeToman', [
'toman' => calculatPrice($this->currencySelect , $this->unit),
]);
}
}
public function render()
{
$currencies = Currency::where('buy_status', 'active')->get();
return view('livewire.frontend.order.buy')->with('currencies', $currencies);
}
}
and this for set value in second input:
<script>
window.addEventListener('changeToman', event => {
$('#toman').val(new Intl.NumberFormat('ir-IR', { maximumSignificantDigits: 3}).format(event.detail.toman));
});
</script>
I assume that calculatPrice is a public method of the component. Don't understand well how every 10 seconds will perform this function if any change in first input is done.
public $calculated, $unit;
public function reCalculate()
{
if($this->unit) { // if input unit has value call the method and assign value
$this->calculated = $this->calculatPrice($this->currencySelect , $this->unit);
}
}
//......
<div wire:poll.10000ms="reCalculate"> // every 10 sec call the method
<input wire:model="unit" type="text" class="form-control" style="text-align: center">
{{ $calculated }}
</div>

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();
}

How to send variable from blade to controller without changing the url

In blade I have a list of books. I want to choose a specific book to show its information. And to do so I want to send with href the id of the book to my controller passing through route.
For example i have
<div class="body text-center">
<h6><b>{{($book->getName())}}</b></h6>
</div>
In href I want to add $bookId = $book->id and the route name so I can call the route with the specific name which calls a method in a controller which can use the variable $bookId
Route::get('/infromation','Books\BookController#index')->name('info');
Here's two propositions:
The first one is to use spatie/laravel-sluggable to have the book name in the URL
The second one is to access the book without changing the URL with a POST request
Using spatie/laravel-sluggable
The slug will be generated automatically from name when the book is created.
your-migration.php
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('slug')->unique()->index();
$table->string('name');
// ...
$table->timestamps();
});
web.php
// Change the URIs as you want. `{book}` is mandatory to retrieve the book though.
Route::get('/books','Books\BookController#index')->name('book.index');
Route::get('/books/{book}','Books\BookController#show')->name('book.show');
Book.php
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Book extends Model
{
use HasSlug;
protected $guarded = [];
public function getSlugOptions()
{
// Adapt with what you want
return SlugOptions::create()
->generateSlugsFrom('name')
->saveSlugsTo('slug')
->doNotGenerateSlugsOnUpdate();
}
public function getRouteKeyName()
{
return 'slug';
}
}
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show(Book $book)
{
// $book is retrieving using Model Binding: https://laravel.com/docs/5.8/routing#route-model-binding
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<a href="{{ route('book.show', $book) }}">
<h6><b>{{ $book->getName() }}</b></h6>
</a>
</div>
Using POST request (URI does not change) and without SLUG
I wouldn't recommend using this for the user experience.
The user cannot bookmark the book or share the link with someone else
When refreshing the page, it will prompt to the user if he want to re-submit the form request
web.php
Route::get('/books','Books\BookController#index')->name('book.index');
Route::post('/books','Books\BookController#show')->name('book.show');
BookController.php
class BookController extends Controller
{
public function index()
{
return view('book.index');
}
public function show()
{
$book = Book::findOrFail(request('book_id'));
return view('book.show', compact('book'));
}
}
index.blade.php
<div class="body text-center">
<form action="{{ route('book.show') }}" method="POST">
#csrf
<input type="hidden" value="{{ $book->id }}" name="book_id">
<h6>
<button type="submit">
<b>{{ $book->getName() }}</b>
</button>
</h6>
</form>
</div>
You can remove the default button style to make it looks like a link
https://stackoverflow.com/a/45890842/8068675
You can try like this
<form action="/BookName/information/<?php echo $book->id; ?>" method="post">
<div class="body text-center">
<input type="hidden" name="book_id" value="{{ $book->id }}">
<a href="/information/<?php echo $book->id; ?>">
<button type="submit" name="book_information" class="btn btn-primary">
<h6>
<b>{{($book->getName())}}</b>
</h6>
</button>
</div>
</form>
// make route like this
Route::post('/BookName/information/{id}','Books\BookController#index');
// Access the that id in controller
public function index(Request $request)
{
echo $request->book_id;
}

Redirection from a vue component to a laravel route

I have a Vue component named searchbox and I want the users to get redirected to display the results once they type the name and click the search button. I am using axios to make the http request. Here's my template:
<form #submit.prevent="searchResult">
<div class="field has-addons searchbox">
<div class="control">
<input class="input" type="text" id="search" name="q" placeholder="Search a video..." #keyup.enter="searchResult" v-model="searchData">
</div>
<div class="control">
<button class="button is-primary"><i class="fa fa-search"></i></button>
</div>
</div>
</form>
Here's my script in the Vue file:
<script>
export default {
data() {
return {
searchData: null,
};
},
methods: {
searchResult() {
axios.get('/search?q=' + this.searchData);
}
}
}
</script>
Here's my search controller:
class SearchController extends Controller {
public function index(Request $request) {
return view('search.index');
}
}
However, I can not see the redirection. How do I redirect from vue component to another route in laravel??
Is vue-router necessary or we can follow any other method??
you can replace axios.get('/search?q=' + this.searchData); with window.location.href = '/search?q=' + this.searchData;

Resources