below is my App/Http/Livewire/Test.php file
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Test extends Component
{
public $name = 'mike';
public function render(){
return view('livewire.test');
}
public function clickTest(){
$this->name = 'Joe';
}
}
below is my resources/views/livewire/test.blade.php
<div>
hello {{$name}}
</div>
and below is my resources/views/test.blade.php
<html>
<head>
<title>test page</title>
#livewireStyles
<script src="{{ asset('js/app.js') }}"></script>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div>
<livewire:test /> //this line is working fine
<button wire:click="clickTest">test</button> //this line is not working
</div>
#livewireScripts
</body>
</html>
I am able to get hello mike on page load but when I click on the test button it's not changing to Joe. When I checked on my network tab, it looks like the click event is not even triggered and it's not able to reach clickTest() function
Your button needs to be moved into the component:
<div>
hello {{$name}}
<button wire:click="clickTest">test</button>
</div>
Related
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
Currently Working on building out a news api behind a dashboard. I have just recently started getting the error Undefined variable: sourceId (View: C:\Laravel8Auth\resources\views\dashboard.blade.php).
Ive gone everywhere that has source Id and I cant see to figure out what it could be.
Here are some of the codes necessary, im using Laravel 8.x with JetStream Im fairly new at this just wanted to mess around.
web php
`<?php
use Illuminate\Support\Facades\Route;
use App\Models\Api;
use App\Http\Controllers\ApiController;
///Route::get('/', [ApiController::class,'displayNews']);
///Route::get('/fetchNewsFromSource', [ApiController::class, 'fetchNewsFromSource'])->name('fetchNewsFromSource');
///Route::post('/sourceId', 'ApiController#displayNews');
Route::get('/', 'App\Http\Controllers\ApiController#displayNews');
Route::post('sourceId', 'App\Http\Controllers\ApiController#displayNews');
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
`
Dashboard php
<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<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>News Application with Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="appendDivNews">
<nav class="navbar fixed-top navbar-light bg-faded" style="background-color: #e3f2fd;">
<a class="navbar-brand" href="#">News Around the World</a>
</nav>
{{ csrf_field() }}
<section id="content" class="section-dropdown">
<p class="select-header"> Select a news source: </p>
<label class="select">
<select name="news_sources" id="news_sources">
<option value="{{$sourceId}} : {{$sourceName}}">{{$sourceName}}</option>
#foreach ($newsSources as $newsSource)
<option value="{{$newsSource['id']}} : {{$newsSource['name'] }}">{{$newsSource['name']}}</option>
#endforeach
</select>
</label>
<object id="spinner" data="spinner.svg" type="image/svg+xml" hidden></object>
</section>
<div id="news">
<p> News Source : {{$sourceName}} </p>
<section class="news">
#foreach($news as $selectedNews)
<article>
<img src="{{$selectedNews['urlToImage']}}" alt=""/>
<div class="text">
<h1>{{$selectedNews['title']}}</h1>
<p style="font-size: 14px">{{$selectedNews['description']}} <a href="{{$selectedNews['url']}}"
target="_blank">
<small>read more...</small>
</a></p>
<div style="padding-top: 5px;font-size: 12px">
Author: {{$selectedNews['author'] ? : "Unknown" }}</div>
#if($selectedNews['publishedAt'] !== null)
<div style="padding-top: 5px;">Date
Published: {{ Carbon\Carbon::parse($selectedNews['publishedAt'])->format('l jS \\of F Y ') }}</div>
#else
<div style="padding-top: 5px;">Date Published: Unknown</div>
#endif
</div>
</article>
#endforeach
</section>
</div>
</div>
</body>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Scripts -->
<script src="{{ asset('js/site.js') }}"></script>
</html>
apicontroller.php supposed to grab from this to get the news api
<?php
namespace App\Http\Controllers;
use App\Models\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ApiController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function displayNews(Request $request)
{
$response = $this->determineMethodHandler($request);
$apiModel = new Api();
$response['news'] = $apiModel->fetchNewsFromSource($response['sourceId']);
$response['newsSources'] = $this->fetchAllNewsSources();
return view('dashboard', $response);
}
/**
* #param $request
* #return mixed
*/
protected function determineMethodHandler($request)
{
if ($request->isMethod('get')) {
$response['sourceName'] = config('app.default_news_source');
$response['sourceId'] = config('app.default_news_source_id');
} else {
$request->validate([
'source' => 'required|string',
]);
$split_input = explode(':', $request->source);
$response['sourceId'] = trim($split_input[0]);
$response['sourceName'] = trim($split_input[1]);
}
return $response;
}
/**
* #return mixed
*/
public function fetchAllNewsSources()
{
$response = Cache::remember('allNewsSources', 22 * 60, function () {
$api = new Api;
return $api->getAllSources();
});
return $response;
}
}
You should pass an array with variables to views
view('dashboard', ["sourceId" => 1, /* and so on */]);
I can't understand what are you doing there.
I created a blog using Laravel, and I am having a weird issue. I pushed my project to Heroku (nepshare.herokuapp.com). When I visit this URL my site loads but with no CSS and I refreshed every time to make it load but failed.
Finally, I changed the https://nepshare.herokuapp.com URL to http://nepshare.herokuapp.com (changed from HTTPS to HTTP) then everything works just fine.css are only loaded in HTTP. How to render all CSS in HTTPS protocol? The following is my main layout code:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
#include('inc.navbar')
<div class="container">
#include('inc.messages')
#yield('content')
</div>
<script src="/vendor/unisharp/laravel-ckeditor/ckeditor.js"></script>
<script>
CKEDITOR.replace('article-ckeditor');
</script>
</body>
</html>
In your .env file define new property,
REDIRECT_HTTPS = true
In your app/Providers/AppServiceProvider.php add this,
namespace App\Providers;
use Illuminate\Routing\UrlGenerator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot(UrlGenerator $url)
{
if(env('REDIRECT_HTTPS')) {
$url->formatScheme('https');
}
}
/**
* Register any application services.
*
* #return void
*/
public function register()
{
if(env('REDIRECT_HTTPS')) {
$this->app['request']->server->set('HTTPS', true);
}
}
}
Now you can use,
<script src="{{ asset('js/app.js') }}" defer></script>
Or you can use secure_asset() helper function but secure_asset() method only use https: https://laravel.com/docs/5.1/helpers#method-secure-asset
secure_asset()
The secure_asset function generates a URL for an asset using HTTPS.
$url = secure_asset('img/photo.jpg');
That's my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Spieler;
class SpielerController extends Controller
{
public function getSpieler(Request $request){
$spielID = $request->get('spielID');
$spielerOutput = Spieler::where('spielPlanID', '=', $spielID)->get();
return view('spieler')->with('alleSpieler', $spielerOutput);
}
}
here you can see my view which I will trigger
#extends('app')
#section('contentSpieler')
<h1>Spieler</h1>
#if(count($alleSpieler) > 0)
#foreach($alleSpieler as $teamSpieler)
{{ $teamSpieler->note }}
#endforeach
#endif
#endsection
And here is my main index/app page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dateneingabe</title>
<link rel="stylesheet" href="/css/app.css">
<script src="{{ asset('/js/jquery-3.2.1.min.js') }}"></script>
</head>
<body>
<div class="container">
<h1>Spiele und Spieler AJAX - Drop Down</h1>
<div class="col-lg-4">
#yield('contentSpiel')
</div>
<div class="col-lg-4">
#yield('contentSpieler')
</div>
</div>
</body>
</html>
When my controller is going to trigger i get back this in my console
<script src="http://localhost:8000/js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<h1>Spiele und Spieler AJAX - Drop Down</h1>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<h1>Spieler</h1> 2.5 Blasdasd
</div>
</div>
</body>
</html>
But I want only that {{ $teamSpieler->note }} should appear in my index/app page in the part #yield('contentSpieler'). What is wrong with my code? The correct value of note 2.5 is in the html console output but at the moment I don't know why there is no output on my index/app page?
if your master view file location is view->index->app.blade.php then
your view file should be like this
#extends('index.app')
#section('contentSpieler')
<h1>Spieler</h1>
#if(count($alleSpieler) > 0)
#foreach($alleSpieler as $teamSpieler)
{{$teamSpieler->note}}
#endforeach
#endif
#endsection
here your master view file location should be correct to extend it in your view file
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>