Information Technology Hub

Stay updated with Information Technology Hub (IT Hub), your premier source for the latest trends, insights, and innovations in information technology. From tech news and tutorials to expert opinions, we provide in-depth articles to keep you informed and ahead in the tech world.

Laravel AI Prompts: Ultimate Guide to Laravel 11 & Livewire v3 Development

--

Learn the power of Laravel AI prompts in our comprehensive guide to Laravel 11 and Livewire v3 development. Learn AI-assisted setup, from models to views, with expert prompts and code examples.

Prompt. Code. Conquer: AI-Assisted Laravel 11 & Livewire v3 Mastery

1. Project Initialization

1.1 Create Laravel Project

AI Prompt for Project Creation

Create a new Laravel 11 project with the following details:
- Project name: [PROJECT_NAME]
- Installation directory: [DIRECTORY_PATH]
Please provide:
1. The exact command to create the project
2. The command to navigate into the project directory
3. A list of key files and directories created, with a brief explanation of each

What AI Needs

  • Desired project name
  • Path where the project should be created

Example AI Response

Based on your request, here are the commands to create and navigate to your new Laravel 11 project:

# Create the new Laravel project
composer create-project laravel/laravel [PROJECT_NAME]
# Navigate into the project directory
cd [PROJECT_NAME]

Key files and directories created:

  • app/ - Contains the core code of your application
  • config/ - All of your application's configuration files
  • database/ - Database migrations and seeders
  • public/ - The entry point for all requests to your application
  • resources/ - Views, raw assets (SASS, JS, etc), and language files
  • routes/ - All of the route definitions for your application
  • .env - Environment-specific configuration file

1.2 Install Livewire

AI Prompt for Livewire Installation

Install Livewire v3 in the Laravel project. Please provide:
1. The command to install Livewire via Composer
2. Any necessary commands to publish Livewire assets or configurations
3. A brief explanation of what each command does

What AI Needs

  • Confirmation that you’re in the project directory

Example AI Response

Assuming you’re in the project directory, here are the commands to install Livewire v3:

# Install Livewire v3
composer require livewire/livewire
# Publish Livewire configuration (optional)
php artisan livewire:publish --config

Explanation:

  • The first command installs Livewire and its dependencies via Composer.
  • The second command publishes the Livewire configuration file to config/livewire.php, allowing you to customize Livewire's behavior.

2. Database Setup

2.1 Configure Database Connection

AI Prompt for Database Configuration

Guide me through setting up the database connection for a Laravel 11 project using MySQL. Please provide:
1. SQL commands to create a new database (if needed)
2. Exact lines to modify in the .env file
3. A command to test the database connection

What AI Needs

  • Database name
  • Database username and password
  • Database host (usually localhost for local development)

Example AI Response

Assuming you’re using MySQL, here’s how to set up your database:

  • Create a new database (if needed):
CREATE DATABASE your_database_name;
  • Modify your .env file in the project root:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
  • Test the database connection:
php artisan tinker
\DB::connection()->getPdo();

If successful, this will return a PDO instance. If it fails, it will throw an exception.

3. Model Creation

3.1 Generate Model

AI Prompt for Model Generation

Create a model named [MODEL_NAME] for the Laravel 11 project. The model should:
1. Use the correct namespace
2. Include fillable properties
3. Define relationships (if any)
4. Use proper PHP 8 syntax including type hinting
Please provide:
1. The Artisan command to generate the model
2. The complete code for the model file, including comments explaining each section

What AI Needs

  • Model name
  • List of fillable attributes
  • Any relationships with other models

Example AI Response

Assuming you want to create a User model:

  • Artisan command to generate the model:
php artisan make:model User
  • Complete code for app/Models/User.php:
<?php
namespace App\Models;use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
/**
* Get the posts for the user.
*/
public function posts()
{
return $this->hasMany(Post::class);
}
}

This model includes fillable properties, attribute casting, and a relationship to a Post model. Adjust the fillable properties and relationships as needed for your specific use case.

4. Migration Creation

4.1 Generate Migration

AI Prompt for Migration Generation

Create a migration for the [TABLE_NAME] table. The migration should:
1. Use the correct naming convention
2. Include appropriate columns with their data types
3. Add any necessary indexes or foreign key constraints
Please provide:
1. The Artisan command to generate the migration
2. The complete code for the migration file, including comments explaining each section

What AI Needs

  • Table name
  • List of columns with their data types
  • Any foreign key relationships or indexes

Example AI Response

Assuming you want to create a migration for a posts table:

  • Artisan command to generate the migration:
php artisan make:migration create_posts_table
  • Complete code for the migration file (e.g., database/migrations/2023_03_15_000000_create_posts_table.php):
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('title');
$table->text('content');
$table->string('slug')->unique();
$table->boolean('is_published')->default(false);
$table->timestamp('published_at')->nullable();
$table->timestamps();

// Add an index on the title column for faster searches
$table->index('title');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('posts');
}
};

This migration creates a posts table with various columns, a foreign key relationship to the users table, and an index on the title column. Adjust the columns and constraints as needed for your specific use case.

5. Factory Creation

5.1 Generate Factory

AI Prompt for Factory Generation

Create a factory for the [MODEL_NAME] model. The factory should:
1. Use the correct namespace
2. Generate realistic fake data for each attribute
3. Handle any relationships by creating related models if necessary
Please provide:
1. The Artisan command to generate the factory
2. The complete code for the factory file, including comments explaining each section

What AI Needs

  • Model name
  • List of attributes to generate fake data for
  • Any specific rules or formats for the fake data

Example AI Response

Assuming you want to create a factory for the Post model:

  • Artisan command to generate the factory:
php artisan make:factory PostFactory
  • Complete code for database/factories/PostFactory.php:
<?php
namespace Database\Factories;use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class PostFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
$title = $this->faker->sentence;
return [
'user_id' => User::factory(),
'title' => $title,
'content' => $this->faker->paragraphs(3, true),
'slug' => Str::slug($title),
'is_published' => $this->faker->boolean(80),
'published_at' => $this->faker->optional(0.8)->dateTimeBetween('-1 year', 'now'),
];
}
/**
* Indicate that the post is published.
*/
public function published(): Factory
{
return $this->state(function (array $attributes) {
return [
'is_published' => true,
'published_at' => $this->faker->dateTimeBetween('-1 year', 'now'),
];
});
}
}

This factory generates fake data for a Post model, including a relationship to a User model. It also includes a published state for creating published posts. Adjust the attributes and fake data generation as needed for your specific use case.

6. Seeder Creation

6.1 Generate Seeder

AI Prompt for Seeder Generation

Create a seeder for the [MODEL_NAME] model. The seeder should:
1. Use the correct namespace
2. Use the factory to create a specified number of records
3. Handle any necessary relationships
Please provide:
1. The Artisan command to generate the seeder
2. The complete code for the seeder file, including comments explaining each section
3. Instructions on how to run the seeder

What AI Needs

  • Model name
  • Number of records to seed
  • Any specific seeding requirements (e.g., creating admin users)

Example AI Response

Assuming you want to create a seeder for the Post model:

  • Artisan command to generate the seeder:
php artisan make:seeder PostSeeder
  • Complete code for database/seeders/PostSeeder.php:
<?php
namespace Database\Seeders;use App\Models\Post;
use App\Models\User;
use Illuminate\Database\Seeder;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// Create 50 posts associated with random users
Post::factory(50)->create();
// Create 5 posts for a specific user (e.g., an admin)
$adminUser = User::where('email', 'admin@example.com')->first();
if ($adminUser) {
Post::factory(5)->create(['user_id' => $adminUser->id]);
}
// Create 10 published posts
Post::factory(10)->published()->create();
}
}
  • Instructions to run the seeder:

First, add the PostSeeder to the run method in database/seeders/DatabaseSeeder.php:

public function run(): void
{
$this->call([
UserSeeder::class, // Assuming you have a UserSeeder
PostSeeder::class,
]);
}

Then, run the seeder using the following Artisan command:

php artisan db:seed

Or, to run only the PostSeeder:

php artisan db:seed --class=PostSeeder

This seeder creates 50 random posts, 5 posts for an admin user (if exists), and 10 published posts. Adjust the numbers and logic as needed for your specific use case.

7. Controller Creation

7.1 Generate Controller

AI Prompt for Controller Generation

Create a controller for the [MODEL_NAME] model. The controller should:
1. Use the correct namespace
2. Include CRUD methods (index, create, store, show, edit, update, destroy)
3. Use proper type hinting and return types
4. Implement basic validation and error handling
Please provide:
1. The Artisan command to generate the controller
2. The complete code for the controller file, including comments explaining each method

What AI Needs

  • Model name
  • Any specific business logic to include in the controller methods

Example AI Response

Assuming you want to create a controller for the Post model:

  • Artisan command to generate the controller:
php artisan make:controller PostController --resource
  • Complete code for app/Http/Controllers/PostController.php:
<?php
namespace App\Http\Controllers;use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
class PostController extends Controller
{
/**
* Display a listing of the posts.
*/
public function index(): View
{
$posts = Post::with('user')->latest()->paginate(15);
return view('posts.index', compact('posts'));
}
/**
* Show the form for creating a new post.
*/
public function create(): View
{
return view('posts.create');
}
/**
* Store a newly created post in storage.
*/
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'title' => 'required|max:255',
'content' => 'required',
'is_published' => 'boolean',
]);
$post = auth()->user()->posts()->create($validated); return redirect()->route('posts.show', $post)
->with('success', 'Post created successfully.');
}
/**
* Display the specified post.
*/
public function show(Post $post): View
{
return view('posts.show', compact('post'));
}
/**
* Show the form for editing the specified post.
*/
public function edit(Post $post): View
{
$this->authorize('update', $post);
return view('posts.edit', compact('post'));
}
/**
* Update the specified post in storage.
*/
public function update(Request $request, Post $post): RedirectResponse
{
$this->authorize('update', $post);
$validated = $request->validate([
'title' => 'required|max:255',
'content' => 'required',
'is_published' => 'boolean',
]);
$post->update($validated); return redirect()->route('posts.show', $post)
->with('success', 'Post updated successfully.');
}
/**
* Remove the specified post from storage.
*/
public function destroy(Post $post): RedirectResponse
{
$this->authorize('delete', $post);
$post->delete(); return redirect()->route('posts.index')
->with('success', 'Post deleted successfully.');
}
}

This controller includes CRUD methods for the Post model, with basic validation and error handling. It assumes you have set up authentication and authorization (using policies). Adjust the logic and validation rules as needed for your specific use case.

8. Livewire Component Creation

8.1 Generate Livewire Component

AI Prompt for Livewire Component Generation

Create a Livewire component for [COMPONENT_NAME]. The component should:
1. Use the correct namespace
2. Include necessary properties and methods
3. Implement any required Livewire lifecycle hooks
4. Handle user interactions and real-time updates
Please provide:
1. The Artisan command to generate the Livewire component
2. The complete code for the component class, including comments explaining each method
3. The complete code for the component's Blade view

What AI Needs

  • Component name
  • Purpose of the component (e.g., form handling, data display)
  • Any specific interactions or real-time features needed

Example AI Response

Assuming you want to create a Livewire component for creating and editing posts:

  • Artisan command to generate the Livewire component:
php artisan make:livewire PostForm
  • Complete code for app/Http/Livewire/PostForm.php:
<?php
namespace App\Http\Livewire;use App\Models\Post;
use Livewire\Component;
class PostForm extends Component
{
public ?Post $post;
public $title = '';
public $content = '';
public $is_published = false;
protected $rules = [
'title' => 'required|min:5|max:255',
'content' => 'required|min:10',
'is_published' => 'boolean',
];
public function mount(?Post $post = null)
{
if ($post) {
$this->post = $post;
$this->title = $post->title;
$this->content = $post->content;
$this->is_published = $post->is_published;
}
}
public function save()
{
$this->validate();
if (isset($this->post)) {
$this->post->update([
'title' => $this->title,
'content' => $this->content,
'is_published' => $this->is_published,
]);
$message = 'Post updated successfully.';
} else {
auth()->user()->posts()->create([
'title' => $this->title,
'content' => $this->content,
'is_published' => $this->is_published,
]);
$message = 'Post created successfully.';
}
$this->reset(['title', 'content', 'is_published']);
session()->flash('success', $message);
$this->emit('postSaved');
}
public function render()
{
return view('livewire.post-form');
}
}
  • Complete code for the component’s Blade view (resources/views/livewire/post-form.blade.php):
<div>
<form wire:submit.prevent="save">
<div class="mb-4">
<label for="title" class="block text-sm font-medium text-gray-700">Title</label>
<input type="text" id="title" wire:model="title" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
@error('title') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
</div>
        <div class="mb-4">
<label for="content" class="block text-sm font-medium text-gray-700">Content</label>
<textarea id="content" wire:model="content" rows="4" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"></textarea>
@error('content') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
</div>
<div class="mb-4">
<label class="inline-flex items-center">
<input type="checkbox" wire:model="is_published" class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50">
<span class="ml-2 text-sm text-gray-600">Publish immediately</span>
</label>
</div>
<div class="flex items-center justify-end">
<button type="submit" class="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-150">
{{ isset($post) ? 'Update' : 'Create' }} Post
</button>
</div>
</form>
</div>

This Livewire component handles both creating and editing posts, with real-time validation and updates. The Blade view uses Tailwind CSS classes for styling. Adjust the styling and functionality as needed for your specific use case.

9. Route Definition

9.1 Define Routes

AI Prompt for Route Definition

Define routes for the [MODEL_NAME] resource. Include:
1. RESTful resource routes
2. Any additional custom routes
3. Route naming and middleware application
Please provide:
1. The complete code to add to the web.php file
2. An explanation of each route and any middleware used

What AI Needs

  • Model name (e.g., Post)
  • Any custom routes beyond standard CRUD operations
  • Whether these are web or API routes

Example AI Response

Assuming we’re creating routes for the Post model, here's how you would define them in routes/web.php:

<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
// Public routes
Route::get('/', [PostController::class, 'index'])->name('home');
Route::get('/posts', [PostController::class, 'index'])->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
// Routes that require authentication
Route::middleware(['auth'])->group(function () {
Route::get('/posts/create', [PostController::class, 'create'])->name('posts.create');
Route::post('/posts', [PostController::class, 'store'])->name('posts.store');
Route::get('/posts/{post}/edit', [PostController::class, 'edit'])->name('posts.edit');
Route::put('/posts/{post}', [PostController::class, 'update'])->name('posts.update');
Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy');
});
// Custom route for publishing a post
Route::post('/posts/{post}/publish', [PostController::class, 'publish'])
->middleware(['auth'])
->name('posts.publish');

Explanation:

  • We define public routes for viewing posts (index and show methods).
  • We group routes that require authentication using the auth middleware.
  • We include all standard CRUD operations (index, create, store, show, edit, update, destroy).
  • We add a custom route for publishing a post, which also requires authentication.
  • All routes are named for easy reference in views and controllers.

10. View Creation

10.1 Create Blade Views

AI Prompt for Blade View Creation

Create Blade views for the [MODEL_NAME] resource. Include templates for:
1. Index page (listing all records)
2. Show page (displaying a single record)
3. Create/Edit form (using the Livewire component we created earlier)
Please provide:
1. The complete Blade template code for each view
2. An explanation of the layout and any Livewire components used

What AI Needs

  • Model name (e.g., Post)
  • Fields to display in each view
  • Any specific layout or styling requirements

Example AI Response

Assuming we’re creating views for the Post model, here are the Blade templates:

  • Index page (resources/views/posts/index.blade.php):
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Posts') }}
</h2>
</x-slot>
    <div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<div class="p-6">
@if (session('success'))
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert">
{{ session('success') }}
</div>
@endif
<div class="mb-4">
<a href="{{ route('posts.create') }}" class="inline-flex items-center px-4 py-2 bg-indigo-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-indigo-700 active:bg-indigo-900 focus:outline-none focus:border-indigo-900 focus:ring ring-indigo-300 disabled:opacity-25 transition ease-in-out duration-150">
Create New Post
</a>
</div>
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Title</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Author</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Published</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
@foreach ($posts as $post)
<tr>
<td class="px-6 py-4 whitespace-nowrap">
<a href="{{ route('posts.show', $post) }}" class="text-indigo-600 hover:text-indigo-900">{{ $post->title }}</a>
</td>
<td class="px-6 py-4 whitespace-nowrap">{{ $post->user->name }}</td>
<td class="px-6 py-4 whitespace-nowrap">
@if ($post->is_published)
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">Published</span>
@else
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">Draft</span>
@endif
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
<a href="{{ route('posts.edit', $post) }}" class="text-indigo-600 hover:text-indigo-900 mr-2">Edit</a>
<form action="{{ route('posts.destroy', $post) }}" method="POST" class="inline-block">
@csrf
@method('DELETE')
<button type="submit" class="text-red-600 hover:text-red-900" onclick="return confirm('Are you sure you want to delete this post?')">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div class="mt-4">
{{ $posts->links() }}
</div>
</div>
</div>
</div>
</div>
</x-app-layout>
  • Show page (resources/views/posts/show.blade.php):
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ $post->title }}
</h2>
</x-slot>
    <div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<div class="p-6">
<div class="mb-4">
<span class="text-gray-600">By {{ $post->user->name }} | {{ $post->created_at->format('F j, Y') }}</span>
</div>
<div class="prose max-w-none">
{!! nl2br(e($post->content)) !!}
</div>
<div class="mt-6">
<a href="{{ route('posts.index') }}" class="text-indigo-600 hover:text-indigo-900">Back to Posts</a>
</div>
</div>
</div>
</div>
</div>
</x-app-layout>
  • Create/Edit form (using Livewire component) (resources/views/posts/create.blade.php and resources/views/posts/edit.blade.php):
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ isset($post) ? 'Edit Post' : 'Create New Post' }}
</h2>
</x-slot>
    <div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<div class="p-6">
@livewire('post-form', ['post' => $post ?? null])
</div>
</div>
</div>
</div>
</x-app-layout>

Explanation:

  • The index page displays a table of all posts with links to view, edit, or delete each post. It uses Tailwind CSS for styling and includes pagination.
  • The show page displays the full content of a single post, including the author and creation date.
  • The create/edit form uses the Livewire component we created earlier (PostForm). This allows for real-time validation and updates without page reloads.
  • All views extend a x-app-layout component, which likely includes the common layout elements like navigation and footer.

These views use Tailwind CSS classes for styling. Adjust the layout and styling as needed for your specific design requirements.

Conclusion

This comprehensive guide walks you through the process of setting up a Laravel 11 and Livewire v3 web application, from project initialization to creating views. By following these steps and customizing the code for your specific needs, you can build a robust, interactive web application with real-time features.

Remember to test your application thoroughly, implement proper error handling and security measures, and optimize your code for performance as you continue to develop your project.

--

--

Information Technology Hub
Information Technology Hub

Published in Information Technology Hub

Stay updated with Information Technology Hub (IT Hub), your premier source for the latest trends, insights, and innovations in information technology. From tech news and tutorials to expert opinions, we provide in-depth articles to keep you informed and ahead in the tech world.

Abu Sayed
Abu Sayed

Written by Abu Sayed

Bangladeshi Full Stack Web Dev, Sys Admin & DevOps Engineer. Skills: Data analysis, SQL, Unity, C#. Python, PHP & Laravel. Me on: bd.linkedin.com/in/imabusayed

No responses yet