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

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');

Related

Livewire component not updating

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.

Why does the old() method not work in Laravel Blade?

My environment is Laravel 6.0 with PHP 7.3. I want to show the old search value in the text field. However, the old() method is not working. After searching, the old value of the search disappeared. Why isn't the old value displayed? I researched that in most cases, you can use redirect()->withInput() but I don't want to use redirect(). I would prefer to use the view(). method
Controller
class ClientController extends Controller
{
public function index()
{
$clients = Client::orderBy('id', 'asc')->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
public function search()
{
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
$query = Client::query();
if (isset($clientID)) {
$query->where('id', $clientID);
}
if ($status != "default") {
$query->where('status', (int) $status);
}
if (isset($nameKana)) {
$query->where('nameKana', 'LIKE', '%'.$nameKana.'%');
}
if (isset($registerStartDate)) {
$query->whereDate('registerDate', '>=', $registerStartDate);
}
if (isset($registerEndDate)) {
$query->whereDate('registerDate', '<=', $registerEndDate);
}
$clients = $query->paginate(Client::PAGINATE_NUMBER);
return view('auth.client.index', compact('clients'));
}
}
Routes
Route::get('/', 'ClientController#index')->name('client.index');
Route::get('/search', 'ClientController#search')->name('client.search');
You just need to pass the variables back to the view:
In Controller:
public function search(Request $request){
$clientID = $request->input('clientID');
$status = $request->input('status');
$nameKana = $request->input('nameKana');
$registerStartDate = $request->input('registerStartDate');
$registerEndDate = $request->input('registerEndDate');
...
return view('auth.client.index', compact('clients', 'clientID', 'status', 'nameKana', 'registerStartDate', 'registerEndDate'));
}
Then, in your index, just do an isset() check on the variables:
In index.blade.php:
<input name="clientID" value="{{ isset($clientID) ? $clientID : '' }}"/>
<input name="status" value="{{ isset($status) ? $status : '' }}"/>
<input name="nameKana" value="{{ isset($nameKana) ? $nameKana : '' }}"/>
...
Since you're returning the same view in both functions, but only passing the variables on one of them, you need to use isset() to ensure the variables exist before trying to use them as the value() attribute on your inputs.
Also, make sure you have Request $request in your method, public function search(Request $request){ ... } (see above) so that $request->input() is accessible.
Change the way you load your view and pass in the array as argument.
// Example:
// Create a newarray with new and old data
$dataSet = array (
'clients' => $query->paginate(Client::PAGINATE_NUMBER),
// OLD DATA
'clientID' => $clientID,
'status' => $status,
'nameKana' => $nameKana,
'registerStartDate' => $registerStartDate,
'registerEndDate' => $registerEndDate
);
// sent dataset
return view('auth.client.index', $dataSet);
Then you can access them in your view as variables $registerStartDate but better to check if it exists first using the isset() method.
example <input type='text' value='#if(isset($registerStartDate)) {{registerStartDate}} #endif />

Laravel 5 (custom) method for calculating age(in days) does not exist

there's a lot of similar questions but I did not find the solution for my problem, so here's the issue:
I have a simple function that should be used for calculating age (in days), listed in the SubmissionController:
public function agingDate($sub) {
$to = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $sub);
$now = Carbon::now();
$diff_in_days->age = $to->diffInDays($now);
return $diff_in_days;
}
Also, in the same controller:
public function index() {
$submission = Submission::orderBy('location_address_state', 'asc')
->get();
return view('/subs/index', [
'submission' => $submission
]);
}
And finally, in my view, I'm trying to call this function:
#if($submission)
#foreach($submission as $sub)
<p>{{ $sub->created_at->agingDate() }}</p>
#endforeach
#endif
The message I'm receiving is "Method agingDate does not exist. (View: /subs/index"). Why can't I access this function - it's in the same controller?
In order to keep the separation of concerns intact, I would suggest that you move your agingDate() method into your submission model.
So, in your Submission model, you could refactor it in the following way:
public function agingDate() {
$to = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $this->created_at);
$now = Carbon::now();
return $to->diffInDays($now);
}
In your blade file, you should then be able to call:
#if($submission)
#foreach($submission as $sub)
<p>{{ $sub->agingDate() }}</p>
#endforeach
#endif
The approach you are currently using doesn't work, since you are trying to call the aging method on a plain property of your Submission instance.

Laravel 5.5 - Save multiple data continiously from blade

I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}

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" />

Resources