I am having issues trying to render my React component within my 'login' view. I am using the Laravel Framework. The page is loaded, however I find no React component in my React Devtools. The Example component provided in the Laravel Project template renders fine. I could not find an error in my syntax, and I was hoping one of you could help me find my error.
My login.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">
<title>Laravel Login</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#200;600&display=swap" rel="stylesheet">
<link href="{{ URL::asset('public/css/app.css') }}">
</head>
<body>
<div id="login-form">
</div>
<script defer src='./js/app.js'> </script>
</body>
</html>
My LoginForm.js
import React from 'react';
import ReactDOM from 'react-dom';
function LoginForm() {
return (
<div class= "container">
Insert FORM here TEST
</div>
);
}
export default LoginForm;
if (document.getElementById('login-form')) {
ReactDOM.render(<LoginForm />, document.getElementById('login-form'));
}
My web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/login', function () {
return view('login');
});
My app.js
require('./bootstrap');
require('./components/Example');
require('./components/LoginForm');
I actually ended up solving this. I changed my LoginForm.js to look like this.
import React, {component} from 'react';
import ReactDOM from 'react-dom';
export default class LoginForm extends React.Component{
render(){
return (
<div class= "container">
Insert FORM here TEST
</div>
);
}
}
if (document.getElementById('login-form')) {
ReactDOM.render(<LoginForm />, document.getElementById('login-form'));
}
Related
I have setup the laravel project with vuejs using #vitejs/plugin-vue plugin, The issue I'm facing is how to manage endpoints between client(vue 3) and backend (laravel 9).
When click register at first time it return the register.vue
When page refresh it returns back 404 error.
welcome.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">
<title>Laravel</title>
<!-- Fonts -->
<link href="https://fonts.bunny.net/css2?family=Nunito:wght#400;600;700&display=swap" rel="stylesheet">
#vite(['resources/js/app.js','resources/css/app.css'])
</head>
<body class="antialiased">
<div id="app"></div>
</body>
</html>
App.vue
<template>
<header>
<!-- load navbar here -->
<nav>
<RouterLink to="/register">Register</RouterLink>
<RouterLink to="/">Home</RouterLink>
</nav>
</header>
<main>
<RouterView/>
</main>
</template>
router.js
import {createRouter, createWebHistory} from "vue-router";
import Register from "../components/Register.vue";
import App from "../../views/App.vue";
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'app',
component: App
},{
path: '/register',
name: 'register',
component: Register
}
]
})
export default router
Quick fix.
In routes/web.php
Route::get('/{any}', function () {
return view('welcome');
})->where("any",".*");
see here
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.
I had a laravel project in a folder "htdocs/webdev/example", i copied the whole "example" folder to another folder "htdocs/Webeng" now that that example folder is not working, it shows the first view but on form submission it says "page not found" however using artisan serve gives correct output
showForm.blade.php
<!-- showForm.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">
<title>Upload File</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<br><br><br>
<!-- store route as action -->
<form action="{{route('uploads')}}" method="post" enctype="multipart/form-data">
#csrf
<!-- value Part -->
<input type="file" class="form-control" name="thing" id="title">
<br>
<input type="submit" class="btn btn-sm btn-block btn-danger" value="Upload" onclick="spinner()">
</form>
#if (session('message'))
<h1 id="t">{{ session('message') }}</h1>
#endif
</div>
</div>
</div>
</body>
</html>
web.php
<?php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('showForm');
})->name("start");
Route::post('/uploads', function (Request $request) {
if($request->file("thing")=="")
{
// return back()->withInput();
return redirect()->route('start')->with('message', 'Insert Data!');
}
else
{
$name=$request->file("thing")->getClientOriginalName();
$book=DB::table('books')->where('Title',$name)->count();
if($book>0)
{
return redirect()->route('start')->with('message', 'Document already exists!');
}
else{
Storage::disk("google")->putFileAs("",$request->file("thing"),$name);
$url=Storage::disk('google')->url($name);
$details=Storage::disk("google")->getMetadata($name);
$path=$details['path'];
DB::insert('insert into books (Title, Url, FileId) values (?,?,?)', [$name,$url,$path]);
return redirect()->route('start')->with('message', 'Successfully uploaded document, you have recieved token!');
}
}
})->name("uploads");
the request moves to http://localhost/Webeng/example/uploads
which is the correct path, in previous folder it was working but now saying page not found
Edit:
corrected the path mistake still same
In showForm.blade.php you are submitting your form to a route called upload.
However, in your routes file you have named the route as uploads
Just change name("uploads") to name("upload") in your routes file and see if it is working
I am creating a simple laravel and vuejs CRUD Application. Vue Routes are not working, I am pretty new to vuejs; please see the code
Below is the code for web.php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/vue','Api\PostController#home');
Route::resource('/api','Api\PostController');
Following is the code for app.js
require('./bootstrap');
window.Vue = require('vue');
window.VueRouter=require('vue-router').default;
window.VueAxios=require('vue-axios').default;
window.Axios=require('axios').default;
let AppLayout = require('./components/App.vue');
const Posts = Vue.component('Posts',require('./components/Posts.vue'));
const EditPost =
Vue.component('EditPost',require('./components/EditPost.vue'));
const AddPost =
Vue.component('AddPost',require('./components/AddPost.vue'));
const DeletePost =
Vue.component('DeletePost',require('./components/AddPost.vue'));
const ViewPosts =
Vue.component('ViewPosts',require('./components/ViewPosts.vue'));
const ExampleComponent =
Vue.component('ViewPosts',require('./components/ExampleComponent.vue'));
// Registering routes
Vue.use(VueRouter,VueAxios,axios);
const routes = [
{
name: 'Posts',
path: '/posts',
component: Posts
},
{
name: 'AddPost',
path: '/add-posts',
component: AddPost
},
{
name: 'EditPost',
path: '/edit-post/:id',
component: EditPost
},
{
name: 'DeletePost',
path: '/delete-post',
component: DeletePost
},
{
name: 'ViewPosts',
path: '/view-post',
component: ViewPosts
},
{
name: 'ExampleComponent',
path: '/example-component',
component: ExampleComponent
},
];
const router = new VueRouter({mode: 'history', routes: routes});
new Vue(
Vue.util.extend(
{ router },
AppLayout
)).$mount('#app');
This is the code of my blade tamplate, when I browse http://localhost:8000/vue this view is being rendered. As you can see in the web.php code above.
I can also see the notification in console You are running Vue in development mode. Make sure to turn on production mode when deploying for production.
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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>
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
<div class="container">
<header class="page-header">
<div class="branding">
<img src="https://vuejs.org/images/logo.png" alt="Logo" title="Home page" class="logo"/>
<h1>Vue.js CRUD With Laravel 5 application</h1>
</div>
</header>
</div>
<section id="app">
</section>
<script>
window.Laravel = <?php echo json_encode([
'csrfToken' => csrf_token(),
]); ?>
</script>
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
But when I run my application using
php artisan serve
and browse to
http://localhost:8000/posts
Application show a 404 error. Please help me with this problem.
You need to add a laravel route for the view where you are using the app.js (vuejs) in routes/web.php file.
Route::get('/route-name/?{name}', function(){
return redirect('vue_app');
})->where('name', '[A-Za-z]+');
and then you have to use the laravel route as a parent route for the vuejs's routes and use the url like below,
http://localhost:8000/laravel-route/view-route
in your case,
http://localhost:8000/route-name/posts
Or you can also use,
Route::get('{any}', function () {
return view('vue_app');
})->where('any', '.*');
and instead of previous use localhost:8000/posts
Try this to your web.php route
Route::get('/', function () {
return view('index');
});
Route::get('/{catchall?}', function () {
return response()->view('index');
})->where('catchall', '(.*)');
if with {any} did not work, you may also try adding ?
Route::get('/any-your-route/{any?}', function() {
return view('your-view');
})->where('any', '.*');
hope this help you. i just try this code and work on laravel blade template with vue router.
Tested on Laravel 8
For your second part of question,
You should use <div> instead of <section> and you have to bring the main/registered component inside of the html element selected by id="app" in blade file. in your case,
<div id="app">
<app-layout></app-layout>
</div>
Hope this help you. you can check this basic vuejs with laravel
PS: You should ask two different problem in two seperate posts.
you can do simply like this.
Route::get('/{vue_capture?}', function(){
return view('welcome');
})->where('vue_capture', '[\/\w\.-]*');
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>