WEB ‐ Laravel ‐ CRUD APP (Part 2) - johnverz22/appdev-lessons GitHub Wiki
Laravel is a PHP framework designed to make web development easier by providing built-in tools for authentication, routing, and database management. It follows the Model-View-Controller (MVC) architecture, ensuring clean code organization.
- Elegant syntax and built-in functions
- Blade templating engine for easy UI rendering
- Eloquent ORM for database operations
- Middleware for request filtering
- Authentication and authorization tools
To install Laravel, follow these steps:
- Install Composer if you haven’t already.
- Open your terminal and run:
composer create-project laravel/laravel my_project
- Navigate to the project folder:
cd my_project
- Start the development server:
php artisan serve
- Open
http://127.0.0.1:8000/
in your browser to see the Laravel welcome page.
Laravel has a structured directory system:
- app/: Contains core logic like models, controllers, and middleware.
- bootstrap/: Loads the framework and initializes the application.
- config/: Stores configuration files.
- database/: Contains migrations, seeders, and factories.
-
public/: Stores entry files like
index.php
and assets like CSS and JS. - resources/: Holds views (Blade templates) and raw assets.
- routes/: Defines web, API, and console routes.
- storage/: Stores logs, cached views, and file uploads.
- tests/: Contains test files.
- vendor/: Houses installed Composer dependencies.
Routes define application URLs and their associated logic. They are stored in routes/web.php
for web applications.
Route::get('/welcome', function () {
return view('welcome');
});
To create a controller, run:
php artisan make:controller HomeController
Then, define methods inside the controller and assign them to routes:
Route::get('/home', [HomeController::class, 'index']);
- Request: The user makes a request (e.g., visiting a URL).
- Routing: Laravel determines which route matches the request.
- Middleware: Filters the request (e.g., authentication checks).
- Controller: Executes business logic and returns a response.
- View: Data is rendered into HTML using Blade.
- Response: The final output is sent to the user.
Laravel uses a .env
file to manage environment-specific settings.
APP_NAME=LaravelApp
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
-
Update
.env
when deploying: EnsureAPP_ENV=production
andAPP_DEBUG=false
for security. -
Clear cache after changes:
php artisan config:clear
Laravel supports multiple databases, but MySQL is commonly used. To configure MySQL:
- Install MySQL and ensure it is running.
- Update the
.env
file with database credentials:DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_db DB_USERNAME=root DB_PASSWORD=
- Run migrations to create necessary tables:
php artisan migrate
Migrations allow version control for the database schema.
- Create a migration:
php artisan make:migration create_users_table
- Edit the generated file in
database/migrations/
. - Example migration:
public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamps(); }); }
- Run the migration:
php artisan migrate
Eloquent ORM simplifies database interactions.
- Create a model:
php artisan make:model User
- Define relationships and attributes inside the model:
class User extends Model { protected $fillable = ['name', 'email']; }
- Fetch data:
$users = User::all();
Example: A Post
has many Comments
.
- Define in
Post
model:public function comments() { return $this->hasMany(Comment::class); }
- Define inverse in
Comment
model:public function post() { return $this->belongsTo(Post::class); }
Example: A User
has many Roles
and vice versa.
- Define in
User
model:public function roles() { return $this->belongsToMany(Role::class); }
- Define in
Role
model:public function users() { return $this->belongsToMany(User::class); }
Laravel Breeze provides a simple authentication setup.
- Install Breeze:
composer require laravel/breeze --dev
- Install authentication scaffolding:
php artisan breeze:install
- Run migrations and serve the app:
php artisan migrate php artisan serve
To manage roles, add a role
column in the users
table:
php artisan make:migration add_role_to_users_table
Modify migration:
$table->string('role')->default('user');
Restrict access based on roles:
if (auth()->user()->role !== 'admin') {
abort(403);
}
Middleware restricts access based on conditions.
- Create middleware:
php artisan make:middleware AdminMiddleware
- Define logic in
app/Http/Middleware/AdminMiddleware.php
:public function handle($request, Closure $next) { if (auth()->user() && auth()->user()->role !== 'admin') { return redirect('/home'); } return $next($request); }
- Register middleware in
app/Http/Kernel.php
:protected $routeMiddleware = [ 'admin' => \App\Http\Middleware\AdminMiddleware::class, ];
- Apply middleware to routes:
Route::get('/admin', function () { return view('admin.dashboard'); })->middleware('admin');
To implement CRUD operations, define routes and create controllers.
- Create a controller:
php artisan make:controller PostController --resource
- Define routes in
routes/web.php
:Route::resource('posts', PostController::class);
- Implement CRUD methods in
PostController.php
:public function index() { $posts = Post::paginate(10); return view('posts.index', compact('posts')); }
- Use Laravel’s form validation:
public function store(Request $request) { $request->validate([ 'title' => 'required|min:3', 'content' => 'required' ]); Post::create($request->all()); return redirect()->route('posts.index')->with('success', 'Post created successfully'); }
- Display validation errors in Blade:
@if ($errors->any()) <div class="text-red-500"> @foreach ($errors->all() as $error) <p>{{ $error }}</p> @endforeach </div> @endif
- Use Laravel’s pagination helper:
<table> @foreach ($posts as $post) <tr> <td>{{ $post->title }}</td> </tr> @endforeach </table> {{ $posts->links() }}
- Edit and update a record:
public function edit(Post $post) { return view('posts.edit', compact('post')); } public function update(Request $request, Post $post) { $post->update($request->all()); return redirect()->route('posts.index')->with('success', 'Post updated'); }
- Delete a record:
public function destroy(Post $post) { $post->delete(); return redirect()->route('posts.index')->with('success', 'Post deleted'); }
- Generate a component:
php artisan make:component Button
- Define props and merge attributes in
resources/views/components/button.blade.php
:@props(['type' => 'button', 'variant' => 'primary']) <button {{ $attributes->merge(['class' => "bg-$variant-500 text-white px-4 py-2 rounded"]) }} type="{{ $type }}"> {{ $slot }} </button>
- Use the component in views with custom props:
<x-button type="submit" variant="blue" class="mt-4">Submit</x-button>
- Install Tailwind CSS:
npm install -D tailwindcss npx tailwindcss init
- Configure
tailwind.config.js
and include Tailwind inresources/css/app.css
:@tailwind base; @tailwind components; @tailwind utilities;
- Apply styles in Blade:
<div class="max-w-xl mx-auto p-6 bg-white shadow-md"> <h1 class="text-xl font-bold">Welcome</h1> </div>
- Store flash messages in the session:
return redirect()->route('posts.index')->with('success', 'Post created');
- Display flash messages in Blade:
@if (session('success')) <div class="bg-green-500 text-white p-2"> {{ session('success') }} </div> @endif
- Set
APP_ENV=production
andAPP_DEBUG=false
in the.env
file. - Update database credentials and other production settings.
- Run the following Artisan commands:
php artisan config:cache php artisan route:cache php artisan view:cache
- Use queues for background tasks:
php artisan queue:work
- Ensure proper permissions for
storage
andbootstrap/cache
:chmod -R 775 storage bootstrap/cache
- Use Nginx or Apache.
- Point the document root to the
public
folder. - Example Nginx configuration:
server { listen 80; server_name example.com; root /var/www/html/laravel/public; index index.php index.html index.htm; location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php/php7.4-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }
- Generate a seeder:
php artisan make:seeder UserSeeder
- Modify the seeder in
database/seeders/UserSeeder.php
:public function run() { User::create([ 'name' => 'Admin', 'email' => '[email protected]', 'password' => bcrypt('password'), ]); }
- Run the seeder:
php artisan db:seed --class=UserSeeder
- Generate a model factory:
php artisan make:factory UserFactory --model=User
- Define fake data in
database/factories/UserFactory.php
:public function definition() { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'password' => bcrypt('password'), ]; }
- Use factories to generate test data:
User::factory()->count(10)->create();