Flash Message Laravel 5.2 using toast materialize - php

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>

Related

How comment script tag content in blade.php?

I try build a React Laravel webpage.
The main.blade.php responsible the layout and that pass data and React components to other blade
I test my app and make few blade.php
So I try comment out several way this line:
/* const data = {{ Illuminate\Support\Js::from($data)}};*/
but not work. It still perceives it as if it were there
I have to pass data for every route for testing because I can't comment the above line
Route::get('/react', function () {
$data = User::find(1);
return view('reactpractice', compact("data"));
})->name('react');
main.blade.php
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/app.css"/>
<title>#yield('title')</title>
<title>{{env('APP_NAME')}}</title>
</head>
<body>
<header>
Motto
</header>
<nav>
Index
About
React
Users
Login
Register
</nav>
#yield('contenttop')
#if(Session::has('successmessage'))
<div class="alert alert-success my-3">
{{Session::get('successmessage')}}
</div>
#endif
#yield('example')
<script>
const data = {{ Illuminate\Support\Js::from($data)}};
const token = '{{#csrf_token()}}'
</script>
<h2> React</h2>
<script src="js/app.js"></script>
</body>
</html>
So how comment script tag content in blade.php?
Rather than comment the line in JavaScript, why not make it conditional?
#if (isset($data))
const data = {{ Illuminate\Support\Js::from($data)}};
#endif
This way, if $data is provided, the JavaScript variable will be created. If $data is missing, it will be ignored and won't break your code.
<!-- Try like this -->
// or /* */
I hope it was helpfull.

Why is Laravel redirecting to wrong path after login?

I have a Laravel 5.8 project.
When I login, it should go to /dashboard.
But it goes to http://localhost:8000/img/favicon/favicon.png
favicon.png is a resource embedded in app.blade.php.
It happens only when I use the auth middleware on route '/dashboard'.
similar problem : Wrong redirection after Login in Laravel, but no solutions.
When I use a
file_put_contents("bugfix.log",print_r($request,true));
in Authenticate.php the problem partially solves but memory exhaust error appears when user is logged out and goes to /dashboard.
app/http/middleware/Authenticate.php (the auth middleware) :
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* #param \Illuminate\Http\Request $request
* #return string
*/
protected function redirectTo($request)
{
// print_r($request,true);
// file_put_contents("bugfix.log",print_r($request,true));
// the above file_put..... code is a strange fix to a problem :
// i.e. when a user logs in he redirects to http://127.0.0.1:8000/js/es6-promise.map in firefox and http://127.0.0.1:8000/img/favicon/favicon.png in chrome
if (! $request->expectsJson()) {
return route('login');
}
return null;
}
}
routes/web.php
<?php
Auth::routes(['verify' => true ]);
Route::get('/logout-manual', function () {
request()->session()->invalidate();
});
Route::get('/', 'HomeController#index')->name('home');
Route::get('/tasks', 'TaskController#alltasks')->name('tasks')->middleware('auth');
Route::get('/login/{provider}', 'Auth\SocialAccountController#redirectToProvider');
Route::get('/login/{provider}/callback', 'Auth\SocialAccountController#handleProviderCallback');
Route::get('/dashboard', 'TaskController#alltasks')->middleware('auth');
Route::get('/{any}', 'TaskController#alltasks')->middleware('auth')->where('any', '.*');
app/http/controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
resources/views/layouts/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">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'abc') }}</title>
<!-- Styles -->
<link href="{{ asset('css/admin.css') }}" rel="stylesheet">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Favicon -->
<link rel="shortcut icon" href="{{ asset('img/favicon/favicon.png') }}">
<!-- Icons -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" rel="stylesheet">
</head>
<body class="d-flex flex-column h-100">
<div id="app" class="flex-shrink-0">
#yield('content')
</div>
<!-- Scripts -->
<script type="application/javascript" src="{{ asset('js/jquery.min.js') }}"></script>
<script type="application/javascript" src="{{ asset('js/app.js') }}" defer></script>
<script type="application/javascript" src="{{ asset('js/abc.js') }}"></script>
<script type="application/javascript" src="{{ asset('js/bootstrap.bundle.min.js') }}"></script>
</body>
</html>
How can I fix this to go to http://localhost:8000/dashboard instead of http://localhost:8000/img/favicon/favicon.png when a user logs in?
It seems like the intended url is overwritten in the session to /img/favicon/favicon.png. Looking at the provided code I'm thinking that your favicon does not exist at that when it's loaded on your login page it triggers your catch all route.
This route uses the auth middleware which triggers the intended url to being set. Since your favicon is loaded on your login page it sets the url to that.
To fix this you could either add the favicon, prefix all routes with e.g./tasks/ or update the regex of the where.
The example below ensures that the route is not matched when the url starts with /img.
Route::get('/{any}', 'TaskController#alltasks')->middleware('auth')->where('any', '^(?!img).*');
Personally I'd move all the assets into an assets directory. This way, instead of excluding /img, /css and /js I'd only have to exclude /assets.

laravel livewire click is not triggering

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>

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

Failed to load CSS in HTTPS protocol

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

Categories