Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active April 3, 2024 02:15
Show Gist options
  • Save abelcallejo/879bac9999cd2f76cebfd37c5b2af669 to your computer and use it in GitHub Desktop.
Save abelcallejo/879bac9999cd2f76cebfd37c5b2af669 to your computer and use it in GitHub Desktop.
Laravel Cheatsheet

Laravel Cheatsheet

Installation

# Prepare the working directory
cd /path/to/www
git clone git@github.com:goodyweb/example-app.git
cd /path/to/www/example-app

# Add the Laravel installer globally all throughout composer
composer global require laravel/installer

# Create new app
laravel new laravel-app

# Get inside the working directory and move all files to the 
cd laravel-app
mv -f ./* ../
mv -f ./.* ../
cd ../
rmdir laravel-app

# Configure the laravel installation
nano .env

# 
php artisan migrate

Breeze

composer require laravel/breeze --dev
php artisan breeze:install

php artisan migrate
npm install
npm run dev

Livewire

composer require livewire/livewire
php artisan livewire:publish --config

resources/views/layouts/app.blade.php

<html>
<head>
    ...
    @livewireStyles
</head>
<body>
    ...
    @livewireScripts
</body>
</html>

Tailwind

# Tailwind
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./resources/**/*.blade.php",
    "./resources/**/*.js",
    "./resources/**/*.vue",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

resources/css/app.css

@tailwind base;
@tailwind components;
@tailwind utilities;
npm run dev

Creating a table

php artisan make:migration create_users_table --create=users

Altering a table

php artisan make:migration add_role_to_users_table --table=users

Deleting a column

$table->dropColumn('status');

Deleting columns

$table->dropColumn(['status', 'status_at']);

Renaming a column

$table->renameColumn('from', 'to');

Changing a column data type

$table->decimal('price', 8, 2)->change();

Data types

Reference

Creating a model

php artisan make:model User

Creating a controller

php artisan make:controller UserController

Getting the current user

use Illuminate\Support\Facades\Auth;

Auth::user()

Creating livewire component

php artisan make:livewire Users

Routing livewire components

use App\Http\Livewire\{Users};

Route::get('/users', Users::class);

Making a command

php artisan make:command SendEmails

Migrating a single migration file forcily

php artisan migrate:refresh --path=database/migrations/timestamped_migration_file.php

Converting strings to slugs

use Illuminate\Support\Str;
$slug = Str::slug('Laravel 5 Framework', '-');

Database

use Illuminate\Support\Facades\DB;

Eloquent

Insert

Article::create(['title' => 'Traveling to Asia']);

Migration file guides

Unique column

$table->string('column_name_here')->unique();

Foreign key

$table->foreign('user_id')->references('id')->on('users');

Calling routes

route('checkout')

or

route('checkout',['uuid'=>$uuid])

Making a seeder

php artisan make:seeder UserSeeder

Hooking a seeder to the main seeder

$this->call([
    UserSeeder::class,
]);

Request parameters

GET or POST parameters that are retrievable.

$_POST['name'] is retrievable as:

request()->name

Also, $_GET['name'] is retrievable similarly as:

request()->name

Relationships

ChatGPT, Laravel Relationships Overview, URL: https://chat.openai.com/share/b60a5e79-0829-4669-a039-16b5e0670b47

File upload

php artisan storage:link

Livewire Component class

<?php

namespace App\Livewire;

use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\Attributes\Validate;
use Illuminate\Support\Str;

class Test extends Component {

    use WithFileUploads;

    #[Validate('image|max:1024')] // 1MB Max
    
    public $photo;

    public function save() {

        // Get the file name of the uploaded file
        $full_file_name = $this->photo->getClientOriginalName();

        // Retrieve parts of the file name
        $parts = pathinfo($full_file_name);

        // Get the visible file name
        $file_name = $parts['filename'];

        // Get the extension file name
        $extension = $parts['extension'];
        
        // Generate a unique identifier
        $uuid = Str::uuid();

        // Generate a unique file name
        $unique_file_name = "{$file_name}.{$uuid}.{$extension}";

        // Store the photo in /path/to/laravel/storage/app/photos
        $this->photo->storeAs('photos', $unique_file_name);
    
    }

    public function render() {
        return view('livewire.test')->layout('layouts.app');
    }

}

Livewire blade

<div>
    <form wire:submit.prevent="save">
        @if ($photo)
        <img src="{{ $photo->temporaryUrl() }}">
        @endif

        <input type="file" wire:model="photo">
        @error('photo') <span class="error">{{ $message }}</span> @enderror
        <button type="submit">Upload</button>
    </form>
</div>

Mail

Mailing with Gmail

  1. Generate an App Password for your Laravel-Gmail integration from myaccount.google.com/apppasswords

  2. It will ask for the App name, just type in Gmail.

    The App name could be of any value really. It is just important to note that it is about Gmail because of all the services of Google, you will be using the Gmail service. You can also put the name of the Laravel application you are building. It is all up to you.

  3. Click the Create button

  4. The Generated app password window will popup

  5. Copy the 12-character password. It will look like so:

    abcd efgh ijkl mnop
    
  6. Remove the spaces to prepare your usable App Password:

    From unusable App Password

    abcd efgh ijkl mnop
    

    into usable App Password

    abcdefghijklmnop
    
  7. Edit the .env configuration file

    nano /path/to/laravel/.env
  8. Edit the following configuration values

    MAIL_MAILER=smtp
    MAIL_HOST=smtp.gmail.com
    MAIL_PORT=465
    MAIL_USERNAME=gmail_username
    MAIL_PASSWORD=gmail_app_password
    MAIL_ENCRYPTION=tls
    MAIL_FROM_ADDRESS="gmail_username@gmail.com"
    MAIL_FROM_NAME="${APP_NAME}"
    • Simply replace all instances of gmail_username with your actual username in Gmail
    • Simply replace gmail_app_password with the usable App Password you prepared in step #6 — the App Password without spaces
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment