laravel livewire delete record renders only after page refresh - laravel

This is my function to delete a search record from the database. I expect the DB changes to be rendered without a page refresh. and that's y I use livewire. but after clicking delete, the page is updated only after refresh. the dd results don't show updated results.
public function deleteSearch($search) {
$empsearch = Auth::user()->mySearches->find($search);
$empsearch->delete();
$this->skills = Auth()->user()->mySearches;
dd($this->skills);
}
Blade file
#if (count($skills) > 0)
#foreach ($skills as $search)
<div class="el-tag" >
<a href="/search?query={{ $search->name }}">
{{ $search->name }}
</a>
|
<a onclick="return confirm('Are you sure?')" wire:click.prevent="deleteSearch({{ $search->search_id }})" >
<i class="pl-1 icon el-icon-delete"></i>
</a>
</div>
#endforeach
#endif
These are the mount and render methods
public $preference;
public $skills;
public function mount($preference) {
$this->preference = $preference;
$this->skills = Auth()->user()->mySearches;
}
public function render() {
return view('livewire.preferences');
}

In the render method, the return statement is returning complete HTML DOM (i.e. return view('livewire.preferences') ) due to which the changes are taking place/reflecting only after the page refresh/reload.
Solution:-
Make the delete request with the help of ajax
Then on success of ajax request, update the main intendent DOM (i.e. the body part) so that the changes will be reflected without page refresh.

after delete statement try this for get fresh data from records
$this->skills = Auth()->user()->mySearches->refresh();
UPDATED
Ok maybe must be only like this:
$this->skills->refresh();

Related

how to get filtered collection backpack laravel

I have a button that needs to pass a filtered collection from a table. Now when I click on the button, I get the entire collection
my button
$this->crud->addButtonFromView('top', 'withdrawDebtCompany', 'withdraw_debt', 'end');
button view
<form action="{{ url($crud->route.'/withdrawAllCompanyDebt') }}" method="POST">
<button class="btn btn-warning" data-style="zoom-in">
<span class="ladda-label">
{{ trans('columns.debt.allwithdraw') }}
</span>
</button>
{{ csrf_field() }}
</form>
method
public function withdrawDebtCompany()
{
$bills = $this->crud->query->get();
Bill::tryWithdrawalsIncrement($bills);
$res['success'] = 0;
$res['err'] = 0;
$bills->each(function($bill) use(&$res){
$paym = new PaymentsController();
$result = $paym->payDebt(new Request([
'bill_id'=>$bill->id,
]));
if($result['code'] == 0) {
$res['success'] += 1;
} else {
$res['err'] += 1;
}
});
\Alert::add('warning', 'Успешно списано: '.$res['success'].' | Неуспешно списано: '. $res['err'])->flash();
return redirect()->back();
}
I tried tracking the filtered collection in the button method, but that doesn't work. This is where the whole collection comes in. Filtered collection only comes after page reload
Hope to find you well.
In your <form> element you don't have any input to be POSTed, so I am wondering, why using a form there and not an <a> or similar.
I would advise you to have a look at the ListOperation https://github.com/Laravel-Backpack/CRUD/blob/main/src/app/Http/Controllers/Operations/ListOperation.php
There you will find the search endpoint that is used by datatables to get it's data.
You can apply a similar solution in your button endpoint to get the filtered results like in table.
Cheers

Livewire display issue when value changes from 0 to 1 or 1 to 0

I have an issue with display updates when updating quantities. I have left/right arrows next to a number in a table to allow the user to change the value of the number, like this:
When the user clicks the left button, a Livewire action triggers that removes an association from a belongs-to-many relationship. When the user clicks the right button, a Livewire action triggers that adds an association to the belongs-to-many relationship.
The Livewire action then refreshes the model, so that the dynamic model property which counts the number of associated records is updated for the Livewire component.
When the number reaches 0, the left arrow disappears. When the number reaches the total quantity available, the right arrow disappears.
Everything about this component works great, except that whenever the values changes from 0 to 1 or from 1 to 0, the numeral disappears from the display:
toggle to 0
toggle to 1
Everything else in my component works flawlessly, including other functionality that relies on the value that disappears. Interacting with any other action in my component causes the number to magically reappear.
If I add a <?php dump($widget->my_associated) ?> to my blade, the correct value gets dumped each time. See example from toggling to 1 or to 4:
This is the code for my component:
shop-widgets.blade.php
<td align="center">
<span style="white-space:nowrap;">
#if ($widget->my_associated)
<i class="fas fa-fw fa-caret-left"></i>
#else
<i class="fas fa-fw"></i>
#endif
{{ $widget->my_associated }}<?php dump($widget->my_associated) ?>
#if ($widget->remaining)
<i class="fas fa-fw fa-caret-right"></i>
#else
<i class="fas fa-fw"></i>
#endif
</span>
</td>
ShopWidgets.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Widget;
class ShopWidgets extends Component
{
public $widget;
public function mount(Widget $widget)
{
$this->widget = $widget;
}
public function render()
{
return view('livewire.shop-widgets', [
'widget' => $this->widget,
]);
}
public function reserve($bought) {
$this->widget->reserve($bought);
$this->widget->refresh();
}
public function release($bought) {
$this->widget->release($bought);
$this->widget->refresh();
}
}
Widget.php
public function reserve($bought)
{
Gate::authorize('reserve', $this);
if ($this->remaining > 0) {
$this->buyers()->attach(Auth::user()->id, ['bought' => $bought]);
}
}
public function release($bought)
{
Gate::authorize('release', $this);
$pivot = $this->buyers()->newPivotStatementForId(Auth::user()->id)->where('bought', $bought);
if ($pivot->count() > 0)
{
$pivot->limit(1)->delete();
}
}
Any idea what might be causing the display issue for this very specific circumstance?
So, after playing around with this a bit more, I realized that the dump is probably displaying correctly because it was inside a <div>. So, I put the number display inside a <span> and it seems to have fixed my issue... <span>{{ $widget->my_associated }}</span>
If anyone knows why this is occurring, I'd be curious to know for troubleshooting future issues...

Post/Get Methode with href and list-group-iteam

I try to build a post/get method with an list group team / href. Here is my code...
#if(count($variableController) > 0)
<ul class="list-group">
#foreach($variableController as $variableView)
{{$variableView->heimmannschaft}}
#endforeach
</ul>
#endif
spielerAuswahl is my view. And after a click on the list-group-item I get to this view. But there I need the information from the list-group-item.
Route::post('/spielerAuswahl', function () {
return 123;
//var_dump($_POST)
});
What I have to do?
replcae post with get method like this:
Route::get('/spielerAuswahl', function () {
return 123;
//var_dump($_POST)
});
if you want to return spielerAuswahl as view
Route::get('/spielerAuswahl', function () {
return view('spielerAuswahl');
});
dont forget
spielerAuswahl.blade.php should be in reousrces/view directory
on the other hand if you want to send some data to view
change route to :
Route::get('/spielerAuswahl/{somevar}', function ($somevar) {
return view('spielerAuswahl',compact('somevar'));
});
and send data like this:
#if(count($variableController) > 0)
<ul class="list-group">
#foreach($variableController as $variableView)
{{$variableView->heimmannschaft}}
#endforeach
</ul>
#endif
it was get method
if you want to use post method your action method should be POST
one way is using <form action="" method="post">

Making object accessible throughout application

I am adding user notifications to my system. To access these notifications for a user, I call an API I have created in another system. So, my IndexController looks something like the following
public function index()
{
if ($user = Sentinel::getUser()) {
$notifications = MyAPI::returnNotifications($user->id);
return view('centaur.dashboard', compact('notifications'));
}
}
Now to problem with the above is that notifications is now only available on the dashboard view. Within my header view I have something like this
#if($notifications)
#foreach($notifications as $notification)
<a class="content" href="#">
<div class="notification-item">
<h4 class="item-title">{{ $notification->subject }}</h4>
<p class="item-info">{{ $notification->body }}</p>
</div>
</a>
#endforeach
#endif
But if I now visit another page besides the dashboard page I get a Undefined variable: notifications error. This is because header is on every page, but I am only passing my notification object to the dashboard page.
Is there any way to make this notification object universally available?
Thanks
UPDATE
if($user = Sentinel::getUser()) {
view()->composer('*', function ($view) {
$view->with('notifications', MyAPI::returnNotifications($user->id));
});
}
You can use a view composer. In your App\Providers\AppServiceProvider#boot method add:
view()->composer('*', function ($view) {
$view->with('notifications', MyAPI::returnNotifications($user->id););
});
Now you'll have the variable $notifications in all of your views. If you want it for specific ones just replace the * with the view name.

CakePHP 1.3 - Send non-form data to controller with js helper

I have a ul of dynamic buttons in my view that appears like the following:
<ul id="dashboard_list">
<li id="id_100" class="btn btn-primary">
<a id="id_100" href="/plugin_name/controller_name/action_name/100">Default View</a>
</li>
<li id="id_200" class="btn btn-primary">
<a id="id_200" href="/plugin_name/controller_name/action_name/200">Second View</a>
</li>
<li id="id_300" class="btn btn-primary">
<a id="id_300" href="/plugin_name/controller_name/action_name/300">Third View</a>
</li>
</ul>
The above links are created using the JSHelper as follows:
echo $this->Html->link($view->name, '/plugin_name/controller_name/action_name/'. $view->id, array('class' => 'ajax-link', 'id'=> $view->id));
I'm using the script below that I found while researching:
// onClick function
function onClick(){
$('#view_container').load($(this).attr('href'), onSuccess);
return false;
}
// activate ajax links to call the onClick function
$('.ajax-link').live('click', onClick);
// onSuccess-callback function
function onSuccess(){}
Now, in my controller / action im doing a simple check for data as follows:
function actionName() {
if ($this->data != null) {
die('We has data!');
}
else
{
die('We has no data.');
}
}
My #view_container element updates properly with "We has no data" on every click. So, I'm obviously not communicating the link's view id number (data) between the view and the controller.
Can anyone offer some direction on how to implement this functionality in CakePHP 1.3 to access the selected id (variable) in the controller? I mostly seem to find form submission examples (or just dead links), and I unfortunately don't have the option to upgrade cakePHP.
FYI: The proper helpers, scripts and the js->writeBuffer are being included.
Thank you for any responses in advance!
Rewrite your function as follows:
function actionName($id) {
debug($id);
if ($this->data != null) {
die('We has data!');
}
else
{
die('We has no data.');
}
}
If you need to do more than one variable in the URL ex:
href="/plugin_name/controller_name/action_name/300/yellow/bannana"
Then your function would look like:
function actionName($id,$color,$fruit) {
}

Resources