Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

koicel's avatar

Creating user roles and permissions in laravel breeze with react js and mysql

Hei folks! I am trying to do what we did in laracasts 8 from scratch. or sort of. So i build a crud, using the laravel kit, laravel breeze, picking reactjs. The issue is, i cannot find and understand how could i do the checks i would normally do in laravel, using @auth and @endauth for example. What I try to achieve, is that I want to build some permissions for guest, users and admins, and i don't see it somehow; after a ton of research I decided to ask here.

As a disclaimer, I am pretty new with php laravel. i only did laracasts so far, and i decided to tackle on a small project by myself but it seems it is so way over my head.

So i got these models: Role

  • role name
  • role id Role permissions:
  • role id
  • permission name User Roles:
  • user id
  • role id And how would i make permissions and verify if the user has registered, for example? because right now I did some stuff in front, and it checks if the viewer is guest, he cannot see the input forms to submit a new post, only if he is logged in. But i feel it's hard coded and it's not the way. In this component I am displaying my jsx components

import React, { useState } from "react"; import CreateAd from "@/Components/CreateAd"; import Header from "@/Components/Header"; import ListedAds from "@/Components/ListedAds"; import { Link, Head } from "@inertiajs/react"; import Footer from "@/Components/Footer";

export default function Welcome({ auth, laravelVersion, phpVersion }) { const [ads, setAds] = useState([]); const [title, setTitle] = useState(""); const [body, setBody] = useState("");

const handleAdCreated = (ad) => {
    setAds((prevAds) => [...prevAds, ad]);
};

const handleAdRemoved = (adId) => {
    setAds((prevAds) => prevAds.filter((ad) => ad.id !== adId));
};

const createPost = (event) => {
    event.preventDefault();

    // Send the form data to the backend API endpoint
    fetch("/api/create-ad", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${auth.token}`,
        },
        body: JSON.stringify({ title, body }),
    })
        .then((response) => response.json())
        .then((data) => {
            // Call the onAdCreated function passed from the parent component
            handleAdCreated(data);

            // Reset the input fields after submitting the post.
            setTitle("");
            setBody("");
        })
        .catch((error) => {
            console.error("Error:", error);
        });
};

return (
    <>
        <Head title="Welcome" />
        <div className="nav-wrapper">
            <p className="placeholder-logo">
                <a href="/">Logo</a>
            </p>
            <div className="navbar">
                {auth.user ? (
                    <Link
                        href={route("dashboard")}
                        className="font-semibold text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white focus:outline focus:outline-2 focus:rounded-sm focus:outline-red-500"
                    >
                        Dashboard
                    </Link>
                ) : (
                    <>
                        <Link
                            href={route("login")}
                            className="font-semibold text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white focus:outline focus:outline-2 focus:rounded-sm focus:outline-red-500"
                        >
                            Log in
                        </Link>

                        <Link
                            href={route("register")}
                            className="ml-4 font-semibold text-gray-600 hover:text-gray-900 dark:text-gray-400 dark:hover:text-white focus:outline focus:outline-2 focus:rounded-sm focus:outline-red-500"
                        >
                            Register
                        </Link>
                    </>
                )}
            </div>
        </div>
        <div className="header">
            <Header />
        </div>
        <div className="listed-ads gap-12">
            {auth.user && (
                <form onSubmit={createPost}>
                    <div>
                        <label htmlFor="title">Title:</label>
                        <input
                            type="text"
                            id="title"
                            value={title}
                            onChange={(event) =>
                                setTitle(event.target.value)
                            }
                        />
                    </div>
                    <div>
                        <label htmlFor="body">Body:</label>
                        <textarea
                            id="body"
                            value={body}
                            onChange={(event) =>
                                setBody(event.target.value)
                            }
                        ></textarea>
                    </div>
                    <button
                        className="create-post-btn rounded mt-2"
                        type="submit"
                    >
                        Create a post
                    </button>
                </form>
            )}
            <ListedAds
                ads={ads}
                onAdRemoved={handleAdRemoved}
                auth={auth}
            />
        </div>
        <Footer />
    </>
);

}

And in this one i do display the created announcements : import React, { useEffect, useState } from "react";

const ListedAds = ({ ads: initialAds, onAdRemoved, auth }) => { const [ads, setAds] = useState(initialAds); const [isLoading, setIsLoading] = useState(false);

const fetchAds = async () => {
    setIsLoading(true);
    try {
        const response = await fetch("/api/get-ads");
        if (response.ok) {
            const data = await response.json();
            setAds(data);
        } else {
            console.error("Error:", response.status);
        }
    } catch (error) {
        console.error("Error:", error);
    } finally {
        setIsLoading(false);
    }
};

useEffect(() => {
    fetchAds();
}, []);

const handleRemoveAd = (adId) => {
    fetch(`/api/remove-ad/${adId}`, {
        method: "DELETE",
    })
        .then((response) => response.json())
        .then((data) => {
            onAdRemoved(adId);
            setAds((prevAds) => prevAds.filter((ad) => ad.id !== adId));
        })
        .catch((error) => {
            console.error("Error:", error);
        });
};

const formatDate = (dateString) => {
    const options = {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "numeric",
        minute: "numeric",
        second: "numeric",
    };
    return new Date(dateString).toLocaleString(undefined, options);
};

return (
    <div className="w-[600px] ads-container">
        <p className="text-2xl mb-2">Currently Listed Ads</p>
        {isLoading ? (
            <p>Loading ads...</p>
        ) : (
            <ul>
                {ads.map((ad) => (
                    <li key={ad.id}>
                        <p className="text-xl bold-50 ad-title">
                            {ad.title}
                        </p>
                        <p className="body-p">{ad.body}</p>
                        <p className="ad-created-at">
                            Created at: {formatDate(ad.created_at)}
                        </p>
                        {auth.user && (
                            <button
                                className="bg-red-500 p-1 rounded mt-2"
                                onClick={() => handleRemoveAd(ad.id)}
                            >
                                Remove
                            </button>
                        )}
                    </li>
                ))}
            </ul>
        )}
    </div>
);

};

export default ListedAds;

while here, we create the ads: import React, { useState } from "react";

const CreateAd = ({ onAdCreated }) => { const [title, setTitle] = useState(""); const [body, setBody] = useState("");

const handleTitleChange = (event) => {
    setTitle(event.target.value);
};

const handleBodyChange = (event) => {
    setBody(event.target.value);
};

const handleSubmit = (event) => {
    event.preventDefault();

    // Send the form data to the backend API endpoint
    fetch("/api/create-ad", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ title, body }),
    })
        .then((response) => response.json())
        .then((data) => {
            // Call the onAdCreated function passed from the parent component
            onAdCreated(data);

            // Reset the input fields after submitting the post.
            setTitle("");
            setBody("");

            // Redirect to homepage
            window.location.href = "/";
        })
        .catch((error) => {
            console.error("Error:", error);
        });
};

return <div></div>;

};

export default CreateAd;

And my controllers:

0 likes
0 replies

Please or to participate in this conversation.