Livewire component not updating - laravel

I have a simple component:
<input type="text" wire:model="search">
{{ $search }}
I load this like this:
#livewire('searchbar')
And this is my class:
class Searchbar extends Component
{
public $search;
public $results = [];
public function updatedSearch()
{
info($this->search);
$this->results = Client::search($this->search)->get();
}
public function render()
{
return view('livewire.searchbar', [
'results' => $this->results,
]);
}
}
When I type into the input field, the info() logs the correct value but in the view, the the {{ $search }} gets not updated. When I use protected $queryString = ['search']; the URL get's updated correctly as well and if I would use dd() instead of info() I'd see the view updating with the dd.
Why is the $search not updating in the view?

Wrap your component. Make sure your Blade view only has ONE root element.
<div>
<input type="text" wire:model="search">
{{ $search }}
</div>

First thing first, inside livewire render, you do not need to send variables.
This will be sufficient.
public function render()
{
return view('livewire.searchbar');
}
You already declared $results as public variable, just like $search.
Livewire will know when the content of those variables are updated.
And now please try again.
$search should be automatically updated based on any text you inserted in input text with wire:model attribute.

Related

Livewire generating a collection on mount, but an array on refresh

I have a (relatively) simple Livewire controller which, on mount() generates a collection of games, grouped by their start dates, and assigns it to the $games public property.
public $games;
protected $rules = [];
...
public function mount() {
$now = Carbon::now();
$games = Game::where('start', '>', $now)->orderBy('start', 'ASC')->get();
$games = $games->groupBy(function($item) {
return $item->start->format("Y-m-d H:i:s");
})->collect();
$this->games = $games;
}
The corresponding component then loops through the dates, outputs the date, and then sends the games themselves to a Blade component (irrelevant styling removed):
#foreach($games as $date => $thegames)
<div>
{{ \Carbon\Carbon::createFromFormat("Y-m-d H:i:s", $date)->format("l jS \of F Y - g:i A") }}
</div>
<div>
<x-individual.game :allgames="$thegames" :user="Auth::user()"></x-individual.game>
</div>
#endforeach
The Blade component then loops through the games that it's been given and renders each of them (simplified below) :
#foreach($allgames as $game)
<div>
<div>
<h3>
{{ $game->game->name }}
</h3>
</div>
</div>
#endforeach
Within that component (not shown) are wire:click buttons which may add a person to the game, or remove them. That, in turn, fires the refresh() function of the original Livewire component, which is identical to the mount() function save that it emits the refreshComponent event at the end :
public function refreshThis() {
$now = Carbon::now();
$games = Game::where('start', '>', $now)->get();
$games = $games->groupBy(function($item) {
return $item->start->format("Y-m-d");
})->collect();
$this->games = $games;
$this->emit('refreshComponent');
}
That's where the problem starts. Rather than re-render the component, as it should, it generates an error of "Attempt to read property "game" on array" within the blade component :
{{ $game->game->name }}
and sure enough, at that point, $game is now an array, not an Eloquent object (or whatever it was first time around).
If I manually refresh the page, the changes are shown without issue. But why is it issuing me an array on refreshing, and (more importantly) how can I stop it?
You could add the $games to the render method instead and it will refresh the data:
public function render()
{
$now = Carbon::now();
$games = Game::where('start', '>', $now)->orderBy('start', 'ASC')->get();
$games = $games->groupBy(function($item) {
return $item->start->format("Y-m-d H:i:s");
})->collect();
return view('livewire.your_component_view', [
'games' => $games
]);
}
Then refresh the component (in your main component):
public function refreshThis() {
$this->render();
}
If you are calling refresh from a child component you can call it form there:
Child component:
$this->emit('refreshThis');

Laravel Livewire - How to force child component refresh

I'd like to refresh the child component when the parent is updated and only the child component of this component should update, because I'd like to reuse the child component somewhere else in the page. The components structure is the following.
UserShow.php
class UserShow extends Component
{
public User $user;
public int $userId;
public function mount() {
$this->user = User::first();
}
public function updatedUserId() {
$this->user = User::find($this->userId);
}
public function render() {
return view('livewire.user-show');
}
}
<div>
<select wire:model="userId">
<option value="1">Matteo</option>
<option value="2">Giulia</option>
<option value="3">Mattia</option>
</select>
<div>
Name: {{ $user->name }}
#livewire('user-show-email', ['user' => $user])
</div>
</div>
UserShowEmail.php
class UserShowEmail extends Component
{
/** #var User */
public $user;
public function render() {
return view('livewire.user-show-email');
}
}
<div>
Email: {{ $user->email }}
</div>
When the user in UserShow is changed via updatedUserId() method, I'd like that $user prop in UserShowEmail will change accordingly. By reading the docs it seems that Livewire is not able to automatically refresh the child component.
I wonder if there's a workaround, or something that allow me to refresh the child component when parent changed.
Thanks!
If you don't mind updating the whole child component, this would be one way of doing it:
There's a trick that always work for me when I want to make a child
Livewire component "reactive". In your parent livewire component you
use a timestamp for the key attribute:
<livewire:child-component key="{{ now() }}" :my-prop="$myModel" />
The tricky part is the now() function in key prop. This component now
will always be updated when the parent is updated.
In your parent component:
<div>
...
<div>
Name: {{ $user->name }}
<livewire:user-show-email key="{{ now() }}" :user="$user" />
</div>
</div>
You can read more about it here and here.

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

Laravel Resource controller for filtering

I have a resource Controller for an API that I'm developing for displaying records that can be filtered by Type and Customer and I have the following methods that can get this data:
index
show -> requires an parameter (id)
Can I therefore put a request inside the index method for filtering all of the entries back or is it bad practise for doing this? My code looks like the following:
public function index()
{
$entries = \App\Ent::where(function($en) {
$request = app()->make('request');
if($request->has('type')) {
$en->where('type', '=', $request->get('type'));
}
if($request->has('customer')) {
$en->where('customer', '=', $request->get('customer'));
}
})->get();
dd($entries);
}
Filtering in Laravel is very simple and you don't need to do this. In your Ent model, define the following:
public function scopeFilter($query, $filters)
{
if( isset($filters['type']) ){
$query->where('type', '=', $filters['type']);
}
// keep going for all of your filters
}
And on your Controller index method you can:
public function index()
{
$entries = \App\Ent::filter(['type', 'customer'])->get();
dd($entries);
}
EDIT
To help you make more sense of this, let's filter Ent on the type column in the database.
Route:
Route::get('/ent', 'EntController#index');
Ent Model:
class Ent extends Model
{
public function scopeFilter($query, $filters)
{
if( isset($filters['type']) ){
$query->where('type', '=', $filters['type']);
}
}
}
Ent Controller:
class EntController extends Controller {
index()
{
$entries = \App\Ent::filter(['type'])->get();
return view('ent.index', compact('entries'));
}
}
Let's say for the sake of this example we are just going to put a form on the same blade template we are outputting our list:
#foreach( $entries as $entry )
<p>{{ $entry->type }}</p>
#endforeach
<form method="GET" action="/ent">
{{ csrf_field() }}
<input type="text" name="type" />
<input type="submit" value="Filter" />
</form>
So now, if I were to go into that form and type 'Foo Bar' and hit submit, you would get what would look something like this in SQL
SELECT * FROM Ent WHERE type='foo bar'
Or in other words, all Ent with the type column = 'foo bar'.
When I give a user the ability to type raw text in to filter, I like to give them the benefit of the doubt and use LIKE instead of =. So for example we would just change our scopeFilter method:
if( isset($filters['type']) ){
$query->where('type', 'LIKE', '%' . $filters['type'] . '%');
}
Another thing to note here, the filters[name] is the name of the <input> field, NOT the name of the column in your database. You target the column in the $query extension, NOT in the $filters array. See below example:
if( isset($filters["ent_type"] ){
$query->where('type', '=', $filters["ent_type"]);
}
On my form that would be
<input name="ent_type" type="text" />

Laravel passing data to page

I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}

Resources