Just started experimenting with Laravel 9 (Inertia + React) and wanted to set up user roles. I tried following the steps in this guide and got it working but now the login/register links on my Navbar layer stops working. The logout link works fine however.
Directly typing and going to 127.0.0.1/login or 127.0.0.1/register works fine and the routes load as they should but clicking the links doesn't do anything (the progress bar moves but after it fills up, nothing happens).
What is causing this? Snippets of my auth.php, web.php, navbar layer and the authenticated/guest layers provided below. Other than the changes shown in the guide and the following files, everything else is default:
auth.php
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\ConfirmablePasswordController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Auth\VerifyEmailController;
use Illuminate\Support\Facades\Route;
Route::middleware('guest')->group(function () {
Route::get('register', [RegisteredUserController::class, 'create'])
->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])
->name('password.request');
Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])
->name('password.email');
Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])
->name('password.reset');
Route::post('reset-password', [NewPasswordController::class, 'store'])
->name('password.update');
});
Route::middleware('auth')->group(function () {
Route::get('verify-email', [EmailVerificationPromptController::class, '__invoke'])
->name('verification.notice');
Route::get('verify-email/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
->middleware(['signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware('throttle:6,1')
->name('verification.send');
Route::get('confirm-password', [ConfirmablePasswordController::class, 'show'])
->name('password.confirm');
Route::post('confirm-password', [ConfirmablePasswordController::class, 'store']);
Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
});
web.php
use App\Http\Controllers\Auth\RedirectAuthenticatedUsersController;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
Route::get('/', function () {
return Inertia::render('Welcome', [
'canLogin' => Route::has('login'),
'canRegister' => Route::has('register'),
'laravelVersion' => Application::VERSION,
'phpVersion' => PHP_VERSION,
]);
});
// Route::get('/dashboard', function () {
// return Inertia::render('Dashboard');
// })->middleware(['auth', 'verified'])->name('dashboard');
Route::group(['middleware' => 'auth'], function() {
Route::inertia('/dashboard', 'Dashboard')->name('dashboard');
Route::get("/redirectAuthenticatedUsers", [RedirectAuthenticatedUsersController::class, "home"]);
Route::group(['middleware' => 'checkRole:admin'], function() {
Route::inertia('/adminDashboard', 'AdminDashboard')->name('adminDashboard');
});
Route::group(['middleware' => 'checkRole:user'], function() {
Route::inertia('/userDashboard', 'UserDashboard')->name('userDashboard');
});
Route::group(['middleware' => 'checkRole:guest'], function() {
Route::inertia('/guestDashboard', 'GuestDashboard')->name('guestDashboard');
});
});
Navbar.jsx
import React, { useState } from 'react';
import ApplicationLogo from '#/Components/ApplicationLogo';
import { Link, usePage } from '#inertiajs/inertia-react';
import Dropdown from '#/Components/Dropdown';
import ResponsiveNavLink from '#/Components/ResponsiveNavLink';
export default function Navbar({ children }) {
const { auth } = usePage().props
const [showingNavigationDropdown, setShowingNavigationDropdown] = useState(false);
return (
<>
<nav className="bg-white border-b border-gray-100">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between h-16">
<div className="flex">
<div className="shrink-0 flex items-center">
<Link href="/">
<ApplicationLogo className="block h-9 w-auto text-gray-500" />
</Link>
<span className="font-semibold text-xl tracking-tight">DrewL Dashboard</span>
</div>
</div>
<div className="hidden sm:flex sm:items-center sm:ml-6">
<div className="ml-3 relative">
<Dropdown>
<Dropdown.Trigger>
<span className="inline-flex rounded-md">
<button
type="button"
className="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 bg-white hover:text-gray-700 focus:outline-none transition ease-in-out duration-150"
>
{auth.user ? (
auth.user.name
) : (
<>
Log In/Register
</>
)}
<svg
className="ml-2 -mr-0.5 h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</button>
</span>
</Dropdown.Trigger>
{auth.user ? (
<Dropdown.Content>
<Dropdown.Link href={route('logout')} method="post" as="button">
Log Out
</Dropdown.Link>
</Dropdown.Content>
) : (
<Dropdown.Content>
<Dropdown.Link href={route('login')} as="button">
Log in
</Dropdown.Link>
<Dropdown.Link href={route('register')} as="button">
Register
</Dropdown.Link>
</Dropdown.Content>
)}
</Dropdown>
</div>
</div>
<div className="-mr-2 flex items-center sm:hidden">
<button
onClick={() => setShowingNavigationDropdown((previousState) => !previousState)}
className="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out"
>
<svg className="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path
className={!showingNavigationDropdown ? 'inline-flex' : 'hidden'}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h16M4 18h16"
/>
<path
className={showingNavigationDropdown ? 'inline-flex' : 'hidden'}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
</div>
</div>
<div className={(showingNavigationDropdown ? 'block' : 'hidden') + ' sm:hidden'}>
<div className="pt-4 pb-1 border-t border-gray-200">
<div className="px-4">
<div className="font-medium text-base text-gray-800">Welcome</div>
<div className="font-medium text-sm text-gray-500">Login now</div>
</div>
<div className="mt-3 space-y-1">
{auth.user ? (
<ResponsiveNavLink href={route('logout')} as="button" method="post" className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0">
Log out
</ResponsiveNavLink>
) : (
<>
<ResponsiveNavLink href={route('register')} as="button" method="post" className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0">
Register
</ResponsiveNavLink>
<ResponsiveNavLink href={route('login')} as="button" method="post" className="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-teal-500 hover:bg-white mt-4 lg:mt-0">
Log in
</ResponsiveNavLink>
</>
)}
</div>
</div>
</div>
</nav>
{children}
</>
);
}
Authenticated.jsx
import React from 'react';
import Navbar from '#/Layouts/Shared/Navbar.jsx';
export default function Authenticated({ auth, header, children }) {
return (
<Navbar>
<div className="min-h-screen bg-gray-100">
{header && (
<header className="bg-white shadow">
<div className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">{header}</div>
</header>
)}
<main>{children}</main>
</div>
</Navbar>
);
}
Guest.jsx
import React from 'react';
import ApplicationLogo from '#/Components/ApplicationLogo';
import { Link } from '#inertiajs/inertia-react';
import Navbar from '#/Layouts/Shared/Navbar.jsx';
export default function Guest({ children }) {
return (
<Navbar>
<div className="min-h-screen bg-gray-100">
<div className="min-h-screen flex flex-col sm:justify-center items-center pt-0 bg-gray-100">
<div>
<Link href="/">
<ApplicationLogo className="w-20 h-20 fill-current text-gray-500" />
</Link>
</div>
<div className="w-full sm:max-w-md mt-6 px-6 py-4 bg-white shadow-md overflow-hidden sm:rounded-lg">
{children}
</div>
</div>
</div>
</Navbar>
);
}
Figured it out. The problem was because I was specifying the method for both login/register as POST requests instead of GET requests. Changing the method for both login and register to GET (as shown below) fixed the issue.
<Dropdown.Link href={route('login')} method="get" as="button">
Log in
</Dropdown.Link>
<Dropdown.Link href={route('register')} method="get" as="button">
Register
</Dropdown.Link>
Related
So I have popup which contains a form that shows a table with editable cells using livewire and each row has a delete button, above this table is a button to add a new empty row to the table. Editing in the cells is working (click the cell and it changes to the inline edit input) but clicking the delete link does nothing and neither does the add link.
So for this process I have the following in the client index file which loads the popup modal when the button to edit the client is clicked.
For this question I am looking at why the add isn't working but as for the delete that would be a bonus!
<script>
$(document).ready(function() {
$("#clients tbody").on("click", ".actions", function () {
var data = table.row( $(this).parents('tr') ).data();
// now call ajax on this url
call_ajax( "/client/" + data[0] + "/edit" );
loader.style.display = "block";
modal.style.display = "block";
});
});
function call_ajax( url ) {
// ToDo make an actual ajax call to get the form data
$.get( url )
.done(
function( data ) {
$("#content-region").html( data );
}
)
.fail(
function() {
$("#content-region").html( "<p>error</p>" );
}
);
}
</script>
So using this when a client has its action section clicked then a call to client/{x}/edit is called which is calls my edit.blade.php file:
#extends('layouts.popup')
#section('header')
<i class="fa fa-fw fa-pencil-square-o fa-lg text-success"></i> Edit Client
#stop
#section('content')
<div class="client-editor">
<form class="admin-link" method="post" action="client/save">
#csrf
<input type="hidden" name="id" value="{{ old( 'id', $client->id ) }}">
<div class="max-w-10xl mx-auto py-10 sm:px-6 lg:px-8">
<div class="md:grid md:grid-cols-3 md:gap-6">
<div class="md:col-span-1 flex justify-between">
<div class="px-4 sm:px-0">
<h3 class="text-lg font-medium text-gray-900">Client Edit</h3>
<p class="mt-1 text-sm text-gray-600">
Update the Client title, you can add and remove contacts below.
</p>
</div>
<div class="px-4 sm:px-0">
</div>
</div>
<div class="mt-5 md:mt-0 md:col-span-2">
<div class="px-4 py-5 bg-white sm:p-6 shadow sm:rounded-tl-md sm:rounded-tr-md">
<!-- Eclipse Account Handler -->
<div class="col-span-6 sm:col-span-4">
<label class="block font-medium text-sm text-gray-700" for="client_id">
Client Title
</label>
<input
class="border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm mt-1 block w-full"
id="title"
name="title"
type="text"
value="{{ $client->title }}"
>
</div>
<br>
<div class="col-span-6 sm:col-span-4">
<x-toggle
left="No"
right="Yes"
name="is_enabled"
label="Is this client active?"
colourleft="#805050"
colourright="#508050"
default="{{ $client->is_enabled }}"
/>
</div>
</div>
<div class="hidden sm:block">
<div class="py-8">
<div class="border-t border-gray-200"></div>
</div>
</div>
</div>
</div>
</div>
<!-- client contacts -->
<div class="max-w-10xl mx-auto py-10 sm:px-6 lg:px-8">
<div class="md:grid md:grid-cols-3 md:gap-6">
<div class="md:col-span-1 flex justify-between">
<div class="px-4 sm:px-0">
<h3 class="text-lg font-medium text-gray-900">Client Contacts</h3>
<p class="mt-1 text-sm text-gray-600">
Enter details for client contacts assigned to this client.
</p>
</div>
</div>
<div class="mt-5 md:mt-0 md:col-span-2">
<div class="px-4 py-5 bg-white sm:p-6 shadow sm:rounded-tl-md sm:rounded-tr-md">
#livewire("contacts-table", [ 'client' => $client ])
</div>
<div
class="flex items-center justify-end px-4 py-3 bg-gray-50 text-right sm:px-6 shadow sm:rounded-bl-md sm:rounded-br-md">
<button
type="submit"
class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring focus:ring-gray-300 disabled:opacity-25 transition"
>
Save
</button>
</div>
<div class="hidden sm:block">
<div class="py-8">
<div class="border-t border-gray-200"></div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
#stop
and from in this a call of #livewire("contacts-table", [ 'client' => $client ]) and this are it's parts.
ContactsTable.php
<?php
namespace App\Http\Livewire;
use App\Models\Client;
use App\Models\ClientContact;
use Livewire\Component;
class ContactsTable extends Component
{
protected $listeners =['refresh' => '$refresh'];
public Client $client;
public $clientContacts;
public function mount( Client $client )
{
$this->clientContacts = ClientContact::where( 'client_id', $client->id )->get();
}
public function render()
{
return view('livewire.contacts-table');
}
public function addNewContact()
{
die('Test that we got here!'); // I actually have a breakpoint here.
}
}
and contacts-table.blade.php:
<div class="col-span-6 sm:col-span-4">
<a
class="inline-flex items-center px-4 py-2 bg-gray-800 dark:bg-gray-100 dark:text-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700 active:bg-gray-900 focus:outline-none focus:border-gray-900 focus:ring focus:ring-gray-300 disabled:opacity-25 transition"
wire:click="addNewContact"
>
{{ __('Add') }}
</a>
<table id="contacts" class="table table-striped table-bordered table-hover">
<thead>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
<td>Action</td>
</thead>
<tbody>
#foreach( $clientContacts as $contact )
<tr id="{{ $contact->id }}">
<td>
#livewire( 'inline-edit', ['item' => $contact, 'type' => 'title', 'number' => $client->id] )
</td>
<td>
#livewire( 'inline-edit', ['item' => $contact, 'type' => 'email', 'number' => $client->id] )
</td>
<td>
#livewire( 'inline-edit', ['item' => $contact, 'type' => 'phone_number', 'number' => $client->id] )
</td>
<td class="width-8">
<a
class="cursor-pointer"
wire:click="$emit( 'openModal', 'delete-contact',{{ json_encode(['contact_id' => $contact->id]) }} )"
>
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<p class="mt-1 text-sm text-gray-600">
Edit the cells above, click the bin to delete or the + to add a new row to populate with a new contact.
</p>
</div>
for completeness here is the popup layout blade file:
<!-- Page Heading-->
<header class="bg-white shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
#yield('header')
</h2>
</div>
</header>
<!-- Page Content -->
<main>
#if (Session::has('message'))
<!-- will be used to show any messages -->
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
<div class="py-12">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
#yield('content')
</div>
</div>
</main>
<!-- End Popup -->
Just to reiterate, the popup form is loading and the content in it is rendered correctly. The top part of the form works so the client is updated.
The inline edit livewire is working (well kind of as I've yet to implement the actual save of it's data but that isn't my issue.
The add button does nothing and nothing is shown in my dev toolbar (no network activity and nothing in the console tab) this is also the case with the delete buttons (which i have working elsewhere in the app - it should show a confirm box and if yes it then removes the contact.
thanks
*** EDIT ***
As an afterthought I have tried this with the client table commented ( the entire table in contacts-table.blade.php) so it just has the add link but it still doesn't work.
*** MORE INFO ***
I have tried removing from the popup and it works this way. Not what I wanted but It does work this way. Why would it not work in a popup?
I've built a nested comment system and it works fine, but I have a problem.
when I want to show the comments, it runs too many queries. for example if I have 10 comments and two replies each, laravel debugger shows 40+ queries, and I want to reduce them, here is my code :
Query
$comments = $post->mentions()->with(['author', 'reply'])->get();
Relationship in Post.php Model
public function mentions()
{
return $this->hasMany(Comment::class, 'post_id')->where('approved',1)->where('parent_id',0);
}
Comments Relationships
public function author()
{
return $this->belongsTo(User::class, 'author_id')->select('id', 'name', 'avatar', 'role');
}
public function reply()
{
return $this->hasMany(Comment::class, 'parent_id')->where('approved', 1);
}
Blade File
#foreach ($comments as $comment)
<div x-data="{reply:false}" class="break-words bg-white border-2 rounded-lg p-4 my-5" id="answer-{1}">
<div wire:ignore class="flex justify-between items-center">
<div class="flex items-center">
<img class="rounded-full w-20 border-4 #if ($comment->author->role == 'administrator') border-blue-500 #else border-gray-500 #endif " src="{{ $comment->author->avatar }}"
alt="{{ $comment->author->name }}">
<div>
<div class="flex pr-3">
<a href="/#username"
class="font-bold text-lg text-gray-800 hover:text-gray-900">{{ $comment->author->name }}</a>
#if ($comment->author->role == 'administrator')
<img class="w-5 mr-1" src="/img/verified.svg" alt="" title="admin">
#endif
</div>
<p class="font-light cursor-default text-gray-700 pt-1 pr-3">
{{ $comment->created_at->diffForHumans() }}</p>
</div>
</div>
<svg #click="reply = true" xmlns="http://www.w3.org/2000/svg" class="h-6 cursor-pointer hover:text-rose-600"
fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
</svg>
</div>
<div class="comment_body leading-8 pt-3 text-gray-800 cursor-default">
<div wire:ignore>
{!! nl2br($comment->body) !!}
</div>
<div x-cloak x-show="reply">
<form class="py-3" wire:submit.prevent="SubmitComment({{ $comment->id }})">
<textarea wire:model.defer="commentBody"
class="w-full focus:ring-0 bg-zinc-200 border shadow focus:bg-zinc-100 mt-3 p-4 rounded-lg"
id="editor" rows="6" placeholder=""></textarea>
#error('commentBody') <p class="text-red-600 mt-1 text-sm">{{ $message }}</p>
#enderror
<div class="flex mt-3">
<div #click="reply = false"
class="bg-red-600 rounded-lg ml-3 text-white px-3 py-2 cursor-pointer">
Cancel
</div>
<button wire:loading.remove wire:target="SubmitComment" type="submit"
class="inline-block bg-gray-800 hover:bg-gray-900 transition duration-300 px-3 py-2 text-white rounded-md">
Send
</button>
<button wire:loading="" wire:target="SubmitComment" type="button"
class="flex bg-gray-800 hover:bg-gray-900 transition duration-300 px-3 py-2 text-white rounded-md"
disabled>
<span class="flex justify-center">
<svg class="animate-spin w-6 h-6" xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z">
</path>
</svg>
</span>
</button>
</div>
</form>
</div>
<div class="my-3">
#include('partials.comment',['comments'=>$comment->reply])
</div>
</div>
</div>
#endforeach
You can use dot seperator to get the nested relationship
$comments = $post->with(['mentions.author','mentions.reply'])
->first()
->mentions;
Weird issue with my Livewire: the validation, when I send a file, always fails on the first time. If I have the criteria that it must be a pdf, I will put the PDF, submit the form, get a message telling me I have the wrong format, I won't change anything, resubmit and it will go through with no issue.
Does anyone knows why it might be happening?
<?php
namespace App\Http\Livewire\Branch\Documents;
use App\Models\BranchDocument;
use Livewire\Component;
use Livewire\WithFileUploads;
class Upload extends Component
{
use WithFileUploads;
public BranchDocument $document;
public $file;
public $saved = false;
public function render()
{
return view('livewire.branch.documents.upload');
}
public function save() {
$this->validate([
'file' => 'mimes:jpg,bmp,png,pdf|max:10240', // 1MB Max
]);
$this->document->file = $this->file;
$this->saved = true;
}
}
<div x-data="{ open: false }">
<li class="#if(!$saved) hover:bg-gray-100 py-2 px-2 rounded cursor-pointer #endif" #click="open = true">
<div class="relative">
<div class="relative flex space-x-3">
<div class="min-w-0 flex-1 flex justify-between space-x-4 items-center">
<div>
<p class="text-sm text-porange">{{ $document->document_type->title }}#if($saved)<span class="text-sm text-gray-600"> - {{ __('Document sent!') }}</span>#endif</p>
<p class="text-xs text-gray-600">{{ $document->created_at->diffForHumans() }}</p>
</div>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" >
#if(!$saved)
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
#else
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
#endif
</svg>
</div>
</div>
</div>
</li>
#if(!$saved)
<div x-show="open" class="fixed z-10 inset-0 overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
<div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<!--
Background overlay, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0"
To: "opacity-100"
Leaving: "ease-in duration-200"
From: "opacity-100"
To: "opacity-0"
-->
<div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
<!-- This element is to trick the browser into centering the modal contents. -->
<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true"></span>
<!--
Modal panel, show/hide based on modal state.
Entering: "ease-out duration-300"
From: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
To: "opacity-100 translate-y-0 sm:scale-100"
Leaving: "ease-in duration-200"
From: "opacity-100 translate-y-0 sm:scale-100"
To: "opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
-->
<div #click.away="open = false" class="inline-block align-bottom bg-white rounded-lg px-4 py-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
<div>
<div class="text-center">
<h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
{{ __('Upload ":title"', ['title' => $document->document_type->title])}}
</h3>
</div>
</div>
<form wire:submit.prevent="save">
<input type="file" wire:model="file" class="file-input-business block mx-auto mt-4"/>
#error('file') <span class="error">{{ $message }}</span> #enderror
<div class="mt-5 sm:mt-6 sm:grid sm:grid-cols-2 sm:gap-3 sm:grid-flow-row-dense">
<button type="submit" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-porange text-base font-medium text-white hover:bg-porange-darker focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-porange sm:col-start-2 sm:text-sm">
{{ __('Send')}}
</button>
<button #click="open = false" type="button" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-porange sm:mt-0 sm:col-start-1 sm:text-sm">
{{ __('Cancel')}}
</button>
</div>
</form>
</div>
</div>
</div>
#endif
</div>
Thank you!
Is the file uploaded before you hit submit? If not then the file is null hence the wrong format error. Check its value in the save method before validation. You can also use wire.loading on a div to determine if the file is still uploading.
You may also run into issues with built in artisan development server (the one you start with php artisan serve command). It has different limitations to a 'real' server - upload file size, formats, etc.
#What I want to do
I want to make a chats system using Laravel,Pusher,ajax.
If the login user is not the item user, a message is sent correctly.
But if I want to send a message to others on the item that made by the login user,
the message will be sent to login user.
I want to know how to fix this issue.But I have no idea...
Route
Route::get('/chats/{receive}/send/{itemId}', [ChatsController::class, 'sendChat'])->name('chats.users');
Route::post('chat/send' , [ChatsController::class, 'store'])->name('chatSend');
blade
<div class="px-4 bg-white text-right sm:px-6">
<a href="{{ route('chats.users',['receive' => $item->user->id ,'itemId'=> $item->id ] ) }}"
type="submit" >チャット </a></div>
Controller
public function sendChat(Request $request, $receive ,$itemId )
{
$loginId = Auth::id();
$param = [
'send' => $loginId,
'receive' => $receive,
];
$query = Message::where('send' , $loginId)->where('receive' , $receive);
$query->orWhere(function($query) use($loginId , $receive){
$query->where('send' , $receive);
$query->where('receive' , $loginId);
});
$messages = $query->get();
$user = User::where('id', $param['receive'])->get();
$item = Item::findOrFail($itemId);
return view('chats.sendChat' , compact('param' , 'messages','user','item'));
}
/**
* Save message
*/
public function store(Request $request)
{
$insertParam = [
'send' => $request->input('send'),
'receive' => $request->input('receive'),
'message' => $request->input('message'),
'user_id' => Auth::user()->id,
'item_id' => $request->input('item_id')
];
try{
Message::insert($insertParam);
}catch (\Exception $e){
return false;
}
return true;
}
messages table
$table->id();
$table->foreignId('user_id')->constrained();
$table->foreignId('item_id')->constrained();
$table->bigInteger('send')->comment('送信者');
$table->bigInteger('receive')->comment('受信者');
$table->text('message');
$table->tinyInteger('is_read')->default(0);
$table->timestamps();
chats.sendChat.blade.php
#extends('layouts.app')
#section('content')
<div class="mt-4">
<div class="m-auto px-4 py-5 mt-2 max-w-xl bg-white rounded-lg " >
<div class="row">
<div class="col-start-2 col-span-4 ">
</div>
</div>
<div id="room" class="justify-items-stretch">
<h1 class="text-lg mb-2">
<a class="no-underline hover:underline text-black" href="{{ route('users.items',[$user[0]->id]) }}">
{{ $user[0]->name }}</a>
{{ $item->title }}
</h1>
<hr>
#foreach($messages as $message)
{{-- Send message --}}
#if($message->send == \Illuminate\Support\Facades\Auth::id())
<div class="flex items-end justify-end">
<div class="send mr-2 bg-green-300 mx-1 my-1 px-1 rounded-lg" style="text-align: right">
<p>{{$message->message}}</p>
</div>
</div>
<p class="text-xs " style="text-align: right">{{ $message->user->name }}</p>
#endif
{{-- received message --}}
#if($message->receive == \Illuminate\Support\Facades\Auth::id())
<div class="flex items-start justify-start">
<div class="receive mr-2 bg-gray-300 mx-1 my-1 px-1 rounded-lg" style="text-align: left">
<p >{{$message->message}}</p>
</div>
</div>
<p class="text-xs ">{{ $message->user->name }}</p>
#endif
#endforeach
</div>
<form >
#csrf
<textarea name="message" style="width:100%" class="mt-1 p-1 focus:outline-none focus:ring focus:border-blue-300 block w-full shadow-sm sm:text-sm border border-indigo-600 rounded-xl"></textarea>
<button type="button" id="btn_send" class="inline-flex justify-center py-2 px-8 mt-1 border border-transparent shadow-sm text-sm font-medium rounded-xl text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 " style="float: right" >
<svg
class="w-4 h-4 transform rotate-45 -mt-px"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
></path>
</svg></button>
</form>
<input type="hidden" name="send" value="{{$param['send']}}">
<input type="hidden" name="receive" value="{{$param['receive']}}">
<input type="hidden" name="login" value="{{\Illuminate\Support\Facades\Auth::id()}}">
<input type="hidden" name="item_id" value="{{$item->id}}">
</div>
</div>
#endsection
javascript
<script type="text/javascript">
var pusher = new Pusher('', {
cluster : '',
encrypted: true
});
var pusherChannel = pusher.subscribe('chat');
pusherChannel.bind('chat_event', function(data) {
let appendText;
let login = $('input[name="login"]').val();
if(data.send === login){
appendText = '<div class="flex items-end justify-end"> <div class="send bg-green-300 mx-1 my-1 p-1 rounded-lg " style="text-align:right"><p>' + data.message + '</p></div></div> ';
}else if(data.receive === login){
appendText = '<div class="receive bg-gray-300 w-3/4 mx-4 my-2 p-2 rounded-lg clearfix" style="text-align:left"><p>' + data.message + '</p></div> ';
}else{
return false;
}
$("#room").append(appendText);
if(data.receive === login){
Push.create("新着メッセージ",
{
body: data.message,
timeout: 8000,
onClick: function () {
window.focus();
this.close();
}
})
}
});
$.ajaxSetup({
headers : {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content'),
}});
// メッセージ送信
$('#btn_send').on('click' , function(){
$.ajax({
type : 'POST',
url : '/chat/send',
data : {
message : $('textarea[name="message"]').val(),
send : $('input[name="send"]').val(),
receive : $('input[name="receive"]').val(),
item_id : $('input[name="item_id"]').val(),
}
}).done(function(result){
$('textarea[name="message"]').val('');
}).fail(function(result){
});
});
</script>
I am building a webapp, but I am having some issues and frankly, I'm confused a bit in terms of how things are functioning. I am still learning as I go, making good progress but sometimes I reach a sticking point this one being one.
This first portion is solved thanks to #kerbholz.
I have the main nav-bar with links setup eg. home, create,
share. When I click my "homepage" it brings me to the sign up/login
view. I don't want that to occur but I rather the logged out user or
visitor see the regular homepage with options to register or click the
login button to arrive at the login screen.
Need help for the below roadblock.
Secondly, when I create a test user it passes the data to the database, but the test user is not actually logged-in prompting the sign up/login view whenever I visit any page. How can I actually ensure the registered user data is accepted as logged-in?
I hope my questions make sense and any help would be greatly appreciated. Code is below, let me know if anything else is missing.
REPO https://github.com/PT-83/FamiJam
Auth Login page
#extends('layouts.app')
#section('content')
<? // Hero Section ?>
<div x-data="{ open: false }" class="relative bg-white overflow-hidden">
<div class="max-w-screen-xl mx-auto ">
<div class="relative z-10 pb-8 bg-white sm:pb-16 md:pb-20 lg:max-w-2xl lg:w-full lg:pb-28 xl:pb-32">
<div class="pt-6 px-4 sm:px-6 lg:px-8">
</div>
<div x-show="open" x-transition:enter="duration-150 ease-out" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100" x-transition:leave="duration-100 ease-in" x-transition:leave-start="opacity-100 scale-100" x-transition:leave-end="opacity-0 scale-95" class="absolute top-0 inset-x-0 p-2 transition transform origin-top-right md:hidden">
<div class="rounded-lg shadow-md">
<div class="rounded-lg bg-white shadow-xs overflow-hidden">
<div class="px-5 pt-4 flex items-center justify-between">
<div>
<img class="h-8 w-auto" src="/img/logos/workflow-mark-on-white.svg" alt="logo" />
</div>
<div class="-mr-2">
<button #click="open = false" type="button" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
</div>
</div>
<div class="mt-10 mx-auto max-w-screen-xl px-4 sm:mt-12 sm:px-6 md:mt-16 lg:mt-20 lg:px-8 xl:mt-28">
<div class="sm:text-center lg:text-left">
<h2 class="text-4xl tracking-tight leading-10 font-extrabold text-gray-900 sm:text-5xl sm:leading-none md:text-6xl">
Remember Your Family
<br class="xl:hidden" />
<span class="text-indigo-600">Culture & Traditions</span>
</h2>
<p class="mt-3 text-base text-gray-500 sm:mt-5 sm:text-lg sm:max-w-xl sm:mx-auto md:mt-5 md:text-xl lg:mx-0">
Family is important, and so are the stories, homemade recepies, remedies and quality time. Now, there's a simply way to store this information and recall all these special moments.
</p>
<p class="mt-3 text-base text-gray-500 sm:mt-5 sm:text-lg sm:max-w-xl sm:mx-auto md:mt-5 md:text-xl lg:mx-0">Famijam is hard at work tyring to complete this application. As progress is being made Famijam is just not ready yet. However, once ready will be sending out beta test oppourtinies to the very first users who registerd. Famijam wants to ensure we are running correctly ensuring stability first and foremost. Thank you!</p>
<div class="mt-5 sm:mt-8 sm:flex sm:justify-center lg:justify-start">
<div class="rounded-md shadow">
<a href="/register" class="w-full flex items-center justify-center px-8 py-3 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:shadow-outline transition duration-150 ease-in-out md:py-4 md:text-lg md:px-10">
Sign up for updates
</a>
</div>
<div class="mt-3 sm:mt-0 sm:ml-3 invisible ">
<a href="#" class="w-full flex items-center justify-center px-8 py-3 border border-transparent text-base leading-6 font-medium rounded-md text-indigo-700 bg-indigo-100 hover:text-indigo-600 hover:bg-indigo-50 focus:outline-none focus:shadow-outline focus:border-indigo-300 transition duration-150 ease-in-out md:py-4 md:text-lg md:px-10">
Live demo
</a>
</div>
</div>
</div>
</div>
<svg class="hidden lg:block absolute right-0 inset-y-0 h-full w-48 text-white transform translate-x-1/2" fill="currentColor" viewBox="0 0 100 100" preserveAspectRatio="none">
<polygon points="50,0 100,0 50,100 0,100" />
</svg>
</div>
</div>
<div class="lg:absolute lg:inset-y-0 lg:right-0 lg:w-1/2">
<img class="h-56 w-full object-cover sm:h-72 md:h-97 lg:w-full lg:h-full" src="/images/fun.svg" alt="Photograp" />
</div>
</div>
<? // End of Hero Section ?>
<? // Features Section ?>
<div class="py-12 bg-white">
<div class="max-w-screen-xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="lg:text-center">
<p class="pt-6 text-base leading-6 text-indigo-600 font-semibold tracking-wide uppercase">Traditions</p>
<h3 class="mt-2 text-3xl leading-8 font-extrabold tracking-tight text-gray-900 sm:text-4xl sm:leading-10">
Share, Learn, Discuss
</h3>
<p class="mt-4 max-w-2xl text-xl leading-7 text-gray-500 lg:mx-auto">
Now more than ever, a place to document family traditions so they will be remembered!
</p>
</div>
<div class="mt-10">
<ul class="md:grid md:grid-cols-2 md:col-gap-8 md:row-gap-10">
<li>
<div class="flex">
<div class="flex-shrink-0">
<div class="flex items-center justify-center h-12 w-12 rounded-md bg-indigo-500 text-white">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9"/>
</svg>
</div>
</div>
<div class="ml-4">
<h5 class="text-lg leading-6 font-medium text-gray-900">Homemade Section</h5>
<p class="mt-2 text-base leading-6 text-gray-500">
Families often make homemade things, this is a great bonding exercise and also a great place to store recipes, how to's, so we can remember and share with each other.
</p>
</div>
</div>
</li>
<li class="mt-10 md:mt-0">
<div class="flex">
<div class="flex-shrink-0">
<div class="flex items-center justify-center h-12 w-12 rounded-md bg-indigo-500 text-white">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3"/>
</svg>
</div>
</div>
<div class="ml-4">
<h5 class="text-lg leading-6 font-medium text-gray-900">Travel Section</h5>
<p class="mt-2 text-base leading-6 text-gray-500">
Did you travel to visit family, or travel for leisure? If so, did you discover any unique restaurants, try new foods, or unique scenery? If so, share these findings in our travel section.
</p>
</div>
</div>
</li>
<li class="mt-10 md:mt-0">
<div class="flex">
<div class="flex-shrink-0">
<div class="flex items-center justify-center h-12 w-12 rounded-md bg-indigo-500 text-white">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"/>
</svg>
</div>
</div>
<div class="ml-4">
<h5 class="text-lg leading-6 font-medium text-gray-900">Family Tree</h5>
<p class="mt-2 text-base leading-6 text-gray-500">
Upload photographs of family members with a brief description or story to share with other friends or family.
</p>
</div>
</div>
</li>
<li class="mt-10 md:mt-0">
<div class="flex">
<div class="flex-shrink-0">
<div class="flex items-center justify-center h-12 w-12 rounded-md bg-indigo-500 text-white">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/>
</svg>
</div>
</div>
<div class="ml-4">
<h5 class="text-lg leading-6 font-medium text-gray-900">Story Time</h5>
<p class="mt-2 text-base leading-6 text-gray-500">
Remember that special moment or story you experienced or were told. Jokes included.
</p>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
<? // End of Feature Section ---?>
<? // Beginning of CTA ------?>
<div class="bg-white mb-20">
<div class="max-w-screen-xl mx-auto py-12 px-4 sm:px-6 lg:py-16 lg:px-8 lg:flex lg:items-center lg:justify-around">
<h2 class="text-3xl leading-9 font-extrabold tracking-tight text-gray-900 sm:text-4xl sm:leading-10">
Ready to Join?
<br />
<span class="text-indigo-600">Start sharing, learning, discussing today.</span>
</h2>
<div class="mt-8 flex lg:flex-shrink-0 lg:mt-0">
<div class="inline-flex rounded-md shadow">
<a href="/register" class="inline-flex items-center justify-center px-10 py-4 border border-transparent text-base leading-6 font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-500 focus:outline-none focus:shadow-outline transition duration-150 ease-in-out">
Get started
</a>
</div>
<div class="ml-3 inline-flex rounded-md shadow invisible">
<a href="#" class="inline-flex items-center justify-center px-5 py-3 border border-transparent text-base leading-6 font-medium rounded-md text-indigo-600 bg-white hover:text-indigo-500 focus:outline-none focus:shadow-outline transition duration-150 ease-in-out">
Learn more
</a>
</div>
</div>
</div>
</div>
#endsection
#section('footer')
#endsection
LoginController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
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 = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('home');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/about', 'HomeController#about')->name('about');
Route::get('/contact', 'HomeController#contact')->name('contact');
Route::post('/register/create', 'Auth\RegisterController#create')->name('register');
Route::get('/post/index', 'PostController#index');
Route::get('/post/create', 'PostController#create');
Route::get('/post/{post}', 'PostController#show');
Route::post('/post', 'PostController#store');
After saving the $user you just registered, use Auth::loginUsingId($user->id); Then redirect to the view or route you want to.
Because all your routes use the same Controller#Action: /share',
'HomeController#index should be /share', 'HomeController#share etc.
(And return view ('/share'); should be return view ('share'); etc) –
kerbholz
The second part regarding the user, laravel takes care of this out of the box. My problem is because I altered the submission form it affected this feature. I will have to play with the form to enable this function to work again. Technically the second portion of the original question is still open, but not necessary to leave this post still unanswered. Thanks to all that helped.