To make the auth layout optional for guests in a Laravel application using React or Vue, you can follow these steps:
-
Create a Shared Layout Component: First, create a layout component that can be used by both authenticated and guest users. This component will serve as a wrapper for your pages.
-
Check Authentication Status: Use Laravel's authentication system to check if a user is authenticated. You can pass this information to your frontend (React or Vue) to conditionally render components.
-
Conditional Rendering: In your React or Vue components, use conditional rendering to display different content based on the user's authentication status.
Here's a basic example for both React and Vue:
React Example
- Create a Layout Component:
// Layout.js
import React from 'react';
const Layout = ({ children, isAuthenticated }) => {
return (
<div>
<header>
<nav>
<a href="/">Home</a>
{isAuthenticated ? (
<a href="/dashboard">Dashboard</a>
) : (
<a href="/login">Login</a>
)}
</nav>
</header>
<main>{children}</main>
</div>
);
};
export default Layout;
- Use the Layout Component:
// App.js
import React from 'react';
import Layout from './Layout';
const App = () => {
// Assume you have a way to determine if the user is authenticated
const isAuthenticated = false; // Replace with actual auth check
return (
<Layout isAuthenticated={isAuthenticated}>
<h1>Welcome to the App</h1>
</Layout>
);
};
export default App;
Vue Example
- Create a Layout Component:
<!-- Layout.vue -->
<template>
<div>
<header>
<nav>
<router-link to="/">Home</router-link>
<router-link v-if="isAuthenticated" to="/dashboard">Dashboard</router-link>
<router-link v-else to="/login">Login</router-link>
</nav>
</header>
<main>
<slot></slot>
</main>
</div>
</template>
<script>
export default {
props: {
isAuthenticated: {
type: Boolean,
required: true
}
}
}
</script>
- Use the Layout Component:
<!-- App.vue -->
<template>
<Layout :isAuthenticated="isAuthenticated">
<h1>Welcome to the App</h1>
</Layout>
</template>
<script>
import Layout from './Layout.vue';
export default {
components: {
Layout
},
data() {
return {
isAuthenticated: false // Replace with actual auth check
};
}
}
</script>
Backend Integration
To pass the authentication status from Laravel to your frontend, you can use a global JavaScript variable or an API endpoint that returns the user's authentication status. For example, you can include a script in your Blade template:
<script>
window.Laravel = {!! json_encode([
'isAuthenticated' => Auth::check(),
]) !!};
</script>
Then, in your frontend code, you can access window.Laravel.isAuthenticated to determine the user's authentication status.
By following these steps, you can create a flexible layout that adapts to both authenticated and guest users, while maintaining a consistent look and feel across your application.