Working with Laravel

01 May 2022 /

Category : Development

Tags : Dev ,Laravel

Post Thumbnail

Simple reference quick for working with Laravel.

These are in sequece Step-by-Step notes based on various online tutorials.

These are on-going notes, code snippet and link references for working with Laravel.

Let’s Sail

If currently running Valet, let’s stop it and use Laravel Sail.

valet stop

From there, let’s download Laravel and start Docker

// download Laravel
curl -s "https://laravel.build/new-app" | bash

cd new-app && ./vendor/bin/sail up

Copy & Paste

./vendor/bin/sail up
./vendor/bin/sail down

PHP Commands

After starting Sail, we can run some PHP commands

sail php --version

Shell

Jump in to shell

sail shell

Add phpMyAdmin to Docker

By default, phpMyAdmin is not within Sail.

Add this to docker-compose.yml

phpmyadmin:
    image: phpmyadmin/phpmyadmin
    links:
        - mysql:mysql
    ports:
        - 8080:80
    environment:
        MYSQL_USERNAME: "${DB_USERNAME}"
        MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
        PMA_HOST: mysql
    networks:
        - sail

Default login is:

sail
password

Migrations

Use Artisan to create database migration

php artisan make:migration create_listings_table

php artisan migrate:refresh --seed
// to clean up migrations 
php artisan migrate:reset

Seed errors

if these seed errors :

SQLSTATE[42S02]: Base table or view not found: 1146 Table

then need to add the table name to the model

public $table = "website";

such as

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Website extends Model
{
    use HasFactory;   

    public $table = "website";
}

Modify tables

Add new fields

public function up()
    {
        Schema::create('listings', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('tags');
            $table->string('company');
            $table->string('location');
            $table->string('email');
            $table->string('website');
            $table->longText('description');
            $table->timestamps();
        });
    }

Eloquent Models

Use Artisan to create a new model

php artisan make:model Listing
// to generate migration
php artisan make:model Listing --migration

Seed the data

Uncomment within DataBaseSeeder.php to create random users


// import model
use App\Models\Listing;

public function run()
    {
         \App\Models\User::factory(10)->create();

           Listing::create([
             'title' => 'Laravel Senior Developer', 
             'tags' => 'laravel, javascript',
             'company' => 'Acme Corp',
             'location' => 'Boston, MA',
             'email' => '[email protected]',
             'website' => 'https:www.acme.com',
             'description' => 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam minima et illo reprehenderit quas possimus voluptas repudiandae cum expedita, eveniet aliquid, quam illum quaerat consequatur! Expedita ab consectetur tenetur delensiti?'
         ]);

    }

then run

php artisan db:seed

to re-fresh the data, run:

php artisan db:refresh

// refresh & seed
php artisan db:refresh --seed

Factory

Create a new factory

https://github.com/bradtraversy/laragigs/blob/main/database/factories/ListingFactory.php

php artisan make:factory ListingFactory

public function definition()
    {
        return [
            'title' => $this->faker->sentence(),
            'tags' => 'laravel, api, backend',
            'company' => $this->faker->company(),
            'email' => $this->faker->companyEmail(),
            'website' => $this->faker->url(),
            'location' => $this->faker->city(),
            'description' => $this->faker->paragraph(5),
        ];
    }

View & Layouts

Laravel View

In ‘views’, create a ’layout.blade.php’ file

@yield('content')

within file (listings.blade.php)

@extends('layout')
@section('content')

@endsection

Images

Place images in ‘public/[new folder called images]’

Route model binding

Mechanism to inject a model instance into your routes

Laravel route model binding provides a convenient way to automatically inject the model instances directly into your routes.

Blade Components

Blade components are a subset of blade template that allow you to create new custom, reusable, encapsulated PHP and HTML

php artisan make:component Alert

Creates 2 files:

app\View\Components\Alert.php
resources\views\components\alert.blade.php

Controllers

Controllers are meant to group associated request handling logic within a single class

Controllers can group related request handling logic into a single class

Controllers are used to handle the request logic within the single class, and the controllers are defined in the “app/http/Controllers” directory. Laravel framework follows the MVC (Model View Controller) architecture in which controllers act as moving the traffic back and forth between model and views.

php artisan make:controller <controller-name> --plain

Add new item

Creting a new form

This could be new listing, posting or other

 <form method="POST" action="/websites" enctype="multipart/form-data">
      @csrf

Routes

within routes (web.php), create the store route

// Store website information
// change to post, calls the store method
Route::post('/websites/',[WebsiteController::class, 'store']);

Controller

Add validation

    // Store data
    public function store(Request $request) 
    {
        //dd($request->all());  // debug
        //validation rules
        $formFields = $request->validate([
            'domain' => 'required',
            // unique table and field
            'url' => ['required|url', Rule::unique('website', 'url')],
            'description' => 'required'
        ]);
        // user model and pass in the formFields
        Website::create($formFields);
        return redirect('/');
    }

Error messages

@error(‘domain’)

Error with domain {{$message}}

@enderror

Model > Add Protected

In model, add fillable

protected $fillable = ['domain', 'url', 'description'];

Flash Message

Resources

Excellent starter video on Laravel Sail

comments powered by Disqus