All livewire functions not firing? - php

For some reason all of the livewire functions in my program have suddenly stopped working and I have no idea why. For example when I click the function to add friend it doesn't fire at all
This is what my app.blade.php part looks like
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght#400;600;700&display=swap">
<!-- Styles -->
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<link href="{{ asset('css/bootstrap.min.css') }}" rel="stylesheet">
<script src="{{ asset('js/app.js') }}" defer></script>
#livewireStyles
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
#livewireScripts
</head>
<body class="font-sans antialiased">
This is what the AddFriend component class looks like:
class AddFriend extends Component
{
// public $user;
public function render()
{
$users = User::where('id', '!=', Auth::user()->id)->limit(14)->latest()->get();
$usersid=User::orderBy('created_at', 'desc')->pluck('id');
$attribute= Attribute::whereIn('user_id',$usersid)->get();
// dd($attribute);
return view('livewire.add-friend', compact('users'));
}
public function addToFriend($id)
{
try {
$user = Auth::user();
$recipient = User::find($id);
if (!$recipient) {
$this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => 'User not found!']);
} else {
if ($user->befriend($recipient)) {
$this->dispatchBrowserEvent('alert', ['type' => 'success', 'message' => 'Request has been sent!']);
} else {
$this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => 'Request has been failed!']);
}
}
} catch (\Exception $e) {
$this->dispatchBrowserEvent('alert', ['type' => 'error', 'message' => $e->getMessage()]);
}
}
This is what the all_users.blade.php looks like:
#extends('layouts.app')
#section('content')
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<article>
<div>
#livewire('add-friend')
</div>
This is the main part where the livewire function gets rendered(add-friend.blade.php):
<div>
#foreach ($users as $user)
<div render:poll="render">
<h3>{{$user->name}}</h3>
#if($user->attributes!=null)
<p>Grade is {{$user->attributes->GradeLevel}}</p>
<p>Age is {{$user->attributes->Age}}</p>
<p>Country is {{$user->attributes->Country}}</p>
#endif
#if(Auth::user()->hasSentFriendRequestTo($user))
<x-button type="submit" class="btn btn-red">Requested</x-button>
#elseif(Auth::user()->isFriendWith($user))
<x-button class="btn btn-green" type="submit" >Friends</x-button>
#else
<button wire:click="addToFriend({{ $user->id }})" class="btn btn-warning" type="button" > Add Friend</button>
#endif
</div>
#endforeach
</div>
I'm not sure what the issue as I'm being told that its to do with the div tags but they all surround the livewire tabs, so I'm not too sure , so it could be anything really. I don't know why all of the livewire functions have all stopped working and normal functions work fine

I can't say for sure, but I'm almost certain you're not supposed to be doing what you're doing in the render() method on your component.
In Livewire, render() is called on each component update, so you really don't want to use it to pass-in attributes like that. Instead, you should create properties on your Livewire component, and use $this->foo in your Blade template to access that data — refreshing state via component methods when necessary.
At the very least, querying your DB on each component render has some pretty bad implications where performance is concerned. You should move this logic into the mount() method on your component, and then store it in a public property for use in your Blade template. Also, where you're iterating in a #foreach, don't forget to include wire:key to help Livewire keep track of what needs updating.
Lastly, I'm not sure what render:poll="render" is in your Blade template. As far as I know, this isn't a Livewire attribute, and I can't find another reference of it in Laravel. Is this something custom or from another package?

Related

Loading a livewire component inside a modal

Description
I am trying to dynamically load a Livewire component inside a modal, using Livewire. I can successfully load the HTML content in the modal, but any Javascript on the "target" component is not executed.
Exact steps to reproduce
<!-- index.blade.php -->
<div>
<a onclick="showTask(1)">Open task #1</a>
#includeWhen($openTask, 'partials.tasks._task_modal')
</div>
//Index.php
function showTask(int $taskId){
$this->managingTask = true;
$this->openTask = Task::firstWhere('id', $taskId);
}
So in the above code, when a user clicks the a tag, it will open the modal, placed in:
<!-- _task_modal.blade.php -->
<x-jet-dialog-modal wire:model="managingTask">
<x-slot name="content">
#livewire('tasks.show', ['task' => $openTask])
</x-slot>
</x-jet-dialog-modal>
As you can see, the modal component simply refers to another Livewire component called tasks.show. Inside this, I have the following in the view file:
<!-- show.blade.php -->
<div>
<a onclick="test()">Test</a>
</div>
#push('scripts')
<script type="text/javascript">
function test(){
alert("It works!")
}
document.addEventListener('livewire:load', function () {
console.log("Livewire Loaded");
});
</script>
#endpush
This is my layout file:
<!-- app.blade.php -->
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link rel="stylesheet" href="{{ mix('css/app.css') }}">
#livewireStyles
<!-- Scripts -->
<script src="{{ mix('js/app.js') }}" defer></script>
</head>
<body class="font-sans antialiased" >
<div id="root" x-data>
{{$slot}}
</div>
#stack('modals')
#livewireScripts
#stack('scripts')
</body>
</html>
Now, when clicking on the a link inside the show.blade.php Livewire component, I get the following error:
Uncaught ReferenceError: test is not defined
Further, I do not see the "Livewire Loaded" in my console.
Context
Livewire version: 2.3.6
Laravel version: 8.12
Browser: Chrome

Flash Message Laravel 5.2 using toast materialize

can you help me solve this problem ? so in this case i want to show flash message in the next page after button click & action (save, update, delete) success perform...
i've read this https://www.tutorialspoint.com/materialize/materialize_dialogs.htm and also http://materializecss.com/dialogs.html but idk how to use it in my controller
public function hapuskeluhan($id){
$keluh = keluhan::findOrFail($id);
$keluh->delete();
return redirect('lihatkeluhan');
}
For Example is function delete, how could my toast appear before it redirect ? or maybe after ? please kindly help me brother
Try this
#if(session('message'))
<script>
Materialize.toast("{{ #session('message') }}", 5000);
</script>
#endif
I think you need to pass the message along with the redirection to be displayed on the view.
public function hapuskeluhan($id)
{
$keluh = keluhan::findOrFail($id);
$keluh->delete();
return redirect('lihatkeluhan')->with(['message', 'Record Deleted!']);
}
and in your view you could access the session variable message as
Materialize.toast({{ session('message') }}, duration, 'rounded');
and initiate a click so that the toast is displayed
$(document).ready(function () {
$("your element containing materialize handle").click();
});
The answer of #Mohammad Arshad is correct. Thank you.
Just to clarify things, I put my code bellow to communicate the system login.
If you want to work with colors, for example, on login success (green) or login fail (red). Just populate the third parameter of materialize toast with 'green' or 'red' respectively.
On UserController.php file:
<?php
namespace App\Http\Controllers\Login;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Hash;
use App\User;
class UserController extends Controller
{
public function login(Request $request)
{
$data = $request->all();
if(Auth::attempt([ 'email'=>$data['email'], 'password'=>$data['password'] ]))
{
\Session::flash('message', ['msg'=>'Login done successfully!', 'class'=>'green']);
return redirect()->route('user.index');
}
\Session::flash('message', ['msg'=>'Login failed. Check your data.', 'class'=>'red']);
return redirect()->route('user.index');
}
}
On site.blade.php file:
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="iso-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config('site.name', 'YourSite') }}</title>
<link rel="stylesheet" type="text/css" href="{{ asset('lib/materialize/dist/css/materialize.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset('css/style.css') }}">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<header>
#include('yourHeaderCode._site._nav')
</header>
<main>
<!-- Your main code -->
#yield('content')
</main>
#include('yourFooterCode._site._footer')
<!-- Scripts -->
<script src="{{ asset('lib/jquery/dist/jquery.js') }}"></script>
<script src="{{ asset('lib/materialize/dist/js/materialize.js') }}"></script>
#if(Session::has('message'))
<script type="text/javascript">
Materialize.toast("{{ Session::get('message')['msg'] }}", 4000, "{{ Session::get('mensagem')['class'] }}");
</script>
#endif()
</body>
</html>

Laravel redirects to login on every page even after logging in

I'm having problems with Laravel since i removed Entrust.
Everything was working fine until i tried installing Entrust. I removed it because it kept saying the following message the same as this question Laravel cache store does not support tagging
Laravel cache store does not support tagging
I removed everything to do with Entrust and removed any changes I had to make but since then whenever I try to go to another page after logging in, it redirects back to the login page. I log back in and it redirects to the dashboard as it should but as soon as i go to another page, it redirects me back to login again.
Any ideas how to fix this?
UPDATE
I think i've narrowed down to the problem.
I created a new project and started again. I created the Auth, created a couple test controllers and views.
I logged in as normal and I got redirected to the Home contoller. I then went to another page and it loaded fine as it should. The views are using the default layout in views/layouts/app.blade.php. As soon as I change it to a custom layout the problem occurs again but is okay if i change it back to app.blade.php
Here is my new default.blade.php but i don't see why this doesn't work anymore
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>#yield('title')</title>
<link rel="icon" type="image/png" href="public/css/favicon-32x32.png" sizes="32x32">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css">
{{ HTML::style('css/bootstrap.css') }}
#if (!empty($styles))
#foreach($styles as $style)
{{ HTML::style($style . '.css') }}
#endforeach
#endif
{{ HTML::style('css/app.css') }}
{{ HTML::style('css/media.css') }}
</head>
<body class="{{ $body_class or '' }}">
<div class="wrapper">
#include('layouts.header')
#yield('content')
<div class="push"></div>
</div>
<div class="footer navbar-primary">
<div class="row">
<div class="col-xs-12">
<footer>
<p>© Copyright #php echo date('Y'); #endphp Axminster Tools & Machinery</p>
</footer>
</div>
</div>
</div>
<script>
window.website_url = '{{ URL::to('/') }}';
</script>
{{ HTML::script('assets/src/jquery/dist/jquery.min.js') }}
{{ HTML::script('assets/src/jquery-ui/jquery-ui.min.js') }}
{{ HTML::script('js/bootstrap.min.js') }}
{{ HTML::script('js/validate.js') }}
#if(isset($jsVars))
<script>
#foreach($jsVars as $key => $val)
var {{ $key }} = {{ $val }};
#endforeach
</script>
#endif
<script>
$(function() {
$("#searchform").submit(function(e) {
$("#searchform").attr("action", "/search/term/" + encodeURI($("#keywords").val()));
});
});
</script>
#if (!empty($scripts))
#foreach($scripts as $script)
{{ HTML::script($script . '.js') }}
#endforeach
#endif
</body>
</html>
I eventually found the problem.
After doing a new installation i tested the Auth and it worked. As soon as I copied across some of my template files I found the problem occurred again. After looking at the template layout files, I found I was using this for the logout link
Change password
I did this within the first few days of learning Laravel and it was never a problem before...don't know why.
I changed it to this and it all works as expected
Logout
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>

My alert doesn't show up in laravel 5

This is my alert.blade.php,
#if(Session::has('info'))
<div class="alert alert-info">{{ Session::get('info') }}</div>
#endif
And this is my welcome.blade.php,
<!DOCTYPE html>
<html>
<head>
<title>Laravel</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
#include('alert')
</body>
</html>
And, here's my routes.php,
Route::get('/', function () {
return view('welcome')->with('info','Hello World');
});
Any help will be really appreciated
Thanks in advance
return view('welcome')->with('info','Hello World');
This line returns the value of 'info' to the view and doesn't set it to the session. While your code:
#if(Session::has('info'))
<div class="alert alert-info">{{ Session::get('info') }}</div>
#endif
checks whether there exists a info variable in the session or not. So you need to change your view to:
#if(isset($info))
<div class="alert alert-info">{{ $info }}</div>
#endif
Which basically would check if the view has a variable called info and if it is true, it prints its value.
Using ->with() will result in a accesible variable inside your view.
You can choose to change it to:
#if (isset($info))
However there are some other cleaner ways to solve this.
You can use the function withErrors()
It would look like:
return view('yourView')->withErrors(['info' => 'Your message'])
And you can access it like:
#if ($errors->has('info'))
{{ $errors->first('info') }}
#endif

Passing variable to view by with not working in laravel 5.1

I want to pass my variable to view by with
this is my controller for example :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Prices ;
class PricesController extends Controller
{
function getIndex()
{
$prices = Prices::orderBy( 'id' , 'desc' )-> paginate(2) ;
return view('home')->nest('content' , 'price', compact('prices') ) ->with( [ 'title' => 'prices page' , 'message' => 'my message text ' ]) ;
}
}
and this is my master.blade.php :
<!doctype html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title> {{ $title }}</title>
<link rel="stylesheet" href="{{ url() }}/css/bootstrap.css">
<link rel="stylesheet" href="{{ url() }}/css/style.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
#yield("main")
</div><!-- container -->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="{{ url() }}/js/bootstrap.min.js"></script>
<script src="{{ url() }}/js/dropdown.js"></script>
<script src="{{ url() }}/js/collapse.js"></script>
<script src="{{ url() }}/js/transition.js"></script>
<script src="{{ url() }}/js/tab.js"></script>
</body>
</html>
and this is home.blade.php :
#extends('master')
#section('main')
#include('top_menu')
<div class="row">
<section class="col-sm-12 col-md-12 content">
<div class="row">
<section class="col-md-12">
<div class="in">
{!! $content !!}
</div>
</section>
</div>
</section>
</div>
#stop
and this is my price.blade.php :
#if( empty($prices) )
<div class="alert alert-warning">
No result
</div>
#else
#if( ! isset( $message) )
No message
#else
{{ $message }}
#endif
<table class="table table-striped">
<tr>
<th>name</th>
<th>yeat</th>
<th>qnty </th>
</tr>
#foreach( $prices as $price )
<tr>
<td> {{$price->product}} </td>
<td> {{$price->yaer}} </td>
<td> {{$price->quantity}} </td>
</tr>
#endforeach
</table>
<center> {!! $prices->render() !!} </center>
#endif
in Output title in <title> {{ $title }}</title> in master.balde.php
is passed good and it will show : prices page in page title , But in this part in price.blade.php :
#if( ! isset( $message) )
No message
#else
{{ $message }}
#endif
the output is :
No maessage
I can access to $message and $title in home.blade.php , But no in price.blade.php
how can I fix it ?
You have an error in a word - maessage, maybe you sending message, but trying to use maessage. Please check it.
Update:
Your code now looks fine. However, look at #if (empty($prices)) part. If (empty($prices) returns true, your code with $message part will never be executed. Probably that's why you don't see my message text.
Update 2:
return view('home')
->nest('content', 'price', array(
'prices' => $prices,
'title' => 'prices page',
'message' => 'my message text'
))
->with([ 'title' => 'prices page', 'message' => 'my message text']);

Categories