Skip to content

Instantly share code, notes, and snippets.

@chaiwei
Last active December 31, 2023 12:20
Show Gist options
  • Save chaiwei/681cd1a4a5f6ae8a8ac49d19cc938324 to your computer and use it in GitHub Desktop.
Save chaiwei/681cd1a4a5f6ae8a8ac49d19cc938324 to your computer and use it in GitHub Desktop.
Laravel
<?php
$users = DB::table('users')->get();
foreach ($users as $user) {
echo $user->name;
}
$user = DB::table('users')->where('name', 'John')->first();
$email = DB::table('users')->where('name', 'John')->value('email');
# Retrieving A List Of Column Values
$titles = DB::table('roles')->pluck('title');
foreach ($titles as $title) {
echo $title;
}
$roles = DB::table('roles')->pluck('title', 'name');
foreach ($roles as $name => $title) {
echo $title;
}
<?php
class modelname extends Model
{
protected $table = 'tablename';
public $timestamps = false;
protected $primaryKey = 'CID'; // or null
public $incrementing = false;
protected $casts = [
'Active' => 'boolean',
];
}
---------------------------------------------------------------
// create
Schema::create('password_resets', function (Blueprint $table) {
// update
Schema::table('users', function ($table) {
// drop
Schema::drop('password_resets');
if (Schema::hasColumn('sales_batches', 'settlement_id')) {
$table->dropColumn(['settlement_id']);
}
->first() Place the column "first" in the table (MySQL Only)
->after('column') Place the column "after" another
column (MySQL Only)
->nullable() Allow NULL values to be inserted into the column
->default($value) Specify a "default" value for the column
->unsigned() Set integer columns to UNSIGNED
->comment('my comment') Add a comment to a column
$table->primary('id'); Add a primary key.
$table->primary(['first', 'last']); Add composite keys.
$table->unique('email'); Add a unique index.
$table->unique('state', 'index_name'); Add a custom index name.
$table->index('state'); Add a basic index.
// column type
$table->increments('id'); Primary key using a "UNSIGNED INTEGER" equivalent.
$table->bigIncrements('id'); Primary key "UNSIGNED BIG INTEGER"
$table->tinyInteger('numbers'); TINYINT equivalent for the database.
$table->smallInteger('votes'); SMALLINT equivalent for the database.
$table->mediumInteger('numbers'); MEDIUMINT equivalent for the database.
$table->integer('votes'); INTEGER equivalent for the database.
$table->bigInteger('votes'); BIGINT equivalent for the database.
$table->decimal('amount', 5, 2); DECIMAL equivalent with a precision and scale.
$table->double('column', 15, 8); DOUBLE, 15 digits in total and 8 after the decimal point.
$table->float('amount'); FLOAT equivalent for the database.
$table->char('name', 4); CHAR equivalent with a length.
$table->string('email'); VARCHAR equivalent column.
$table->string('name', 100); VARCHAR equivalent with a length.
$table->text('description'); TEXT equivalent for the database.
$table->mediumText('description'); MEDIUMTEXT equivalent for the database.
$table->longText('description'); LONGTEXT equivalent for the database.
$table->binary('data'); BLOB equivalent for the database.
$table->boolean('confirmed'); BOOLEAN equivalent for the database.
$table->date('created_at'); DATE equivalent for the database.
$table->dateTime('created_at'); DATETIME equivalent for the database.
$table->dateTimeTz('created_at'); DATETIME (with timezone) equivalent for the database.
$table->time('sunrise'); TIME equivalent for the database.
$table->timeTz('sunrise'); TIME (with timezone) equivalent for the database.
$table->timestamp('added_on'); TIMESTAMP equivalent for the database.
$table->timestampTz('added_on'); TIMESTAMP (with timezone) equivalent for the database.
$table->timestamps(); Adds created_at and updated_at columns.
$table->enum('choices', ['foo', 'bar']); ENUM equivalent for the database.
$table->ipAddress('visitor'); IP address equivalent for the database.
$table->json('options'); JSON equivalent for the database.
$table->jsonb('options'); JSONB equivalent for the database.
$table->macAddress('device'); MAC address equivalent for the database.
$table->morphs('taggable'); Adds INTEGER taggable_id and STRING taggable_type.
$table->nullableTimestamps(); Same as timestamps(), except allows NULLs.
$table->rememberToken(); Adds remember_token as VARCHAR(100) NULL.
$table->softDeletes(); Adds deleted_at column for soft deletes.
$table->uuid('id'); UUID equivalent for the database.
ALTER TABLE `TABLE_NAME`
ADD `created_at` TIMESTAMP NULL AFTER `LAST_COLUMN_NAME`,
ADD `updated_at` TIMESTAMP NULL AFTER `created_at`,
ADD `deleted_at` TIMESTAMP NULL AFTER `updated_at`;
// select query
$lists = \App\Models\fbalbum::paginate(50);

// insert query
$post = \App\Models\fbalbum::create(array(
	'album_name' => $request->input('album_name'),
	'album_id'=> $request->input('album_id'),
));

// update query
$post = \App\Models\fbalbum::find($id);
$post->album_id = $request->input('album_id');
$post->album_name = $request->input('album_name');
$post->save();

// delete query
$post = \App\Models\fbalbum::find($id);
$post->delete();


// skip = OFFSET, take = LIMIT
$users = DB::table('users')
	->skip(10)
	->take(5)
	->get();
$users = DB::table('users')
	->offset(10)
	->limit(5)
	->get();
$total = OrderInvoice::whereHas('order', function(Builder $query) {
    $user = Auth::user();
    $query->where('status', 'completed');
    $query->where('seller_id', $user->id);
}) 
->sum('net_payment_to_seller');
// sql
select sum(`net_payment_to_seller`) as aggregate 
from `fr_order_invoices` 
where exists (
    select * from `fr_order_transactions` 
    where `fr_order_invoices`.`order_id` = `fr_order_transactions`.`id` 
    and `status` = ? 
    and `seller_id` = ?
)
$total = OrderInvoice::query()
    ->join('fr_order_transactions as t', 'fr_order_invoices.order_id', '=', 't.id')
    ->where('t.status', 'completed')
    ->where('t.seller_id', $user->id)
    ->where('fr_order_invoices.status', 'paid')
    ->sum('net_payment_to_seller');
// sql
select sum(`net_payment_to_seller`) as aggregate 
from `fr_order_invoices` 
inner join `fr_order_transactions` as `t` 
    on `fr_order_invoices`.`order_id` = `t`.`id` 
where `t`.`status` = ? 
and `t`.`seller_id` = ? 
and `fr_order_invoices`.`status` = ?
<form>
{{ method_field('PUT') }}
{{ csrf_field() }}
</form>
flowchart TD
    START((Model))
    START       --> UPDATE[Update]
    UPDATE      -->|Fill| SAVE{Save \n fa:fa-bolt saving}
    SAVE        -->|Check exists| EXISTS{Record Exists?}
    EXISTS      -->|Yes| UPDATING{Perform Update \n fa:fa-bolt updating}
    UPDATING    -->|Update Record| UPDATED[Update \n fa:fa-bolt updated]
    UPDATED     -->|Record Updated| SAVED[Finish Save \n fa:fa-bolt saved]
    SAVED       -->|Saved Successfully| END
    START       -->|__call:Builder| CREATE[Create]
    CREATE      -->|New Model Instance| SAVE
    EXISTS      -->|No| CREATING{Perform Insert \n fa:fa-bolt creating}
    CREATING    -->|Create Record| CREATED[Insert \n fa:fa-bolt created]
    CREATED     -->|Record Created| SAVED
    START       --> DELETE[Delete] 
    DELETE      --> |Check exists| DEL_EXISTS{Record Exists?}
    DEL_EXISTS  -->|Yes| DELETING_1{Delete \n fa:fa-bolt deleting}
    DELETING_1  --> DELETING_2[touchOwners]
    DELETING_2  -->|Delete Record| DELETING_3[performDeleteOnModel]
    DELETING_3  -->|Record Deleted| DELETED[Delete \n fa:fa-bolt deleted]
    DELETED     --> END
    DEL_EXISTS  -->|No| END
    END((End))
Loading
Str::macro('maskEmail', function (string $value) {
    $pattern = "/[^@\s]*@[^@\s]*\.[^@\s]*/";
    $replacement = "[removed]";
    return preg_replace($pattern, $replacement, $value);
});
Str::macro('maskPhoneNumber', function (string $value) {
    $pattern = "/\+?[0-9][0-9()\-\s+]{4,20}[0-9]/";
    $replacement = "[removed]";
    return preg_replace($pattern, $replacement, $value);
});
<?php
use Illuminate\Support\Facades\Log;
Log::info('Showing user profile for user: '.$id);
Log::info('User failed to login.', ['id' => $user->id]);
Log::channel('slack')->info('Something happened!');
Log::stack(['single', 'slack'])->info('Something happened!');
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);
<?php
Session::flash('danger', 'Security token expired. Please retry.');
return redirect('seller/orders/'.$order->id)->with('success', ['Invoice Paid.']);
return redirect('/seller/orders/' . $id)
->withErrors([
'error' => 'Customer has accepted the offer #'.$order->acceptedOffer->first()->id.' previously.'
]);
if ($request->inertia()) {
// If request is from inertia,
return Inertia::location($response->url);
} else {
return redirect()->away('https://www.google.com');
}
<?php

namespace Modules\Core\Rules;

use Laravel\Fortify\Rules\Password as FortifyPasswordRule;
use Illuminate\Support\Str;

class Password extends FortifyPasswordRule
{
    protected $requireLowercase = false;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        if ($this->requireLowercase && Str::upper($value) === $value) {
            return false;
        }
        return parent::passes($attribute, $value);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        if ($this->message) {
            return $this->message;
        }
        $message = 'The :attribute must be at least :length characters';
        
        $andMessage = [];
        if ($this->requireUppercase) {
            $andMessage[] = 'one uppercase character';
        }
        if ($this->requireLowercase) {
            $andMessage[] = 'one lowercase character';
        }
        if ($this->requireNumeric) {
            $andMessage[] = 'one number';
        }
        if ($this->requireSpecialCharacter) {
            $andMessage[] = 'one special character';
        }
        if (!empty($andMessage)) {
            $message .= ' and contain at least ';
            foreach ($andMessage as $loopIndex => $loopValue) {
                if ($loopIndex === 0){
                    $message .= $loopValue;
                } else if ($loopIndex === (count($andMessage) - 1)) {
                    $message .= ' and ' . $loopValue;
                } else {
                    $message .= ', ' . $loopValue;
                }
            }
        }
        $message = $message . '.';
        return __($message, [
            'length' => $this->length,
        ]);
    }

    /**
     * Indicate that at least one lowercase character is required.
     *
     * @return $this
     */
    public function requireLowercase()
    {
        $this->requireLowercase = true;

        return $this;
    }
}
<?php

namespace App\Actions\Fortify;

use Modules\Core\Rules\Password;

trait PasswordValidationRules
{
    /**
     * Get the validation rules used to validate passwords.
     *
     * @return array
     */
    protected function passwordRules()
    {   
        $passwordLength = 8;
        $requirement = (new Password)
            ->length($passwordLength)
            ->requireUppercase()
            ->requireLowercase()
            ->requireNumeric()
            ->requireSpecialCharacter();
        return ['required', 'string', $requirement];
    }
}
<?php
Route::get('foo', function () {
return 'Hello World';
});
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Route::resource('photo', 'PhotoController');
Route::resource('photo', 'PhotoController', ['only' => [
'index', 'show'
]]);
Route::resource('photo', 'PhotoController', ['except' => [
'create', 'store', 'update', 'destroy'
]]);
Route::resource('photo', 'PhotoController', ['names' => [
'create' => 'photo.build'
]]);
Route::resource('user', 'AdminUserController', ['parameters' => [
'user' => 'admin_user'
// generates the /user/{admin_user} URIs for the resource's show route
]]);
Route::resource('users.photos', 'PhotoController', [
'parameters' => 'singular'
// /users/{user}/photos/{photo}
]);
GET /photo index photo.index
GET /photo/create create photo.create
POST /photo store photo.store
GET /photo/{photo} show photo.show
GET /photo/{photo}/edit edit photo.edit
PUT/PATCH /photo/{photo} update photo.update
DELETE /photo/{photo} destroy photo.destroy
Route::match(['get', 'post'], '/', function () {
//
});
Route::any('foo', function () {
//
});
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
});
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
Route::get('user/{name}', function ($name) {
})->where('name', '[A-Za-z]+');
Route::get('user/{id}', function ($id) {
})->where('id', '[0-9]+');
Route::get('user/{id}/{name}', function ($id, $name) {
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);
Route::get('user/profile', ['as' => 'profile', function () {
}]);
Route::get('user/profile', [
'as' => 'profile', 'uses' => 'UserController@showProfile'
]);
Route::get('user/profile', 'UserController@showProfile')->name('profile');

Validation

class StoreResumePersonal extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [
            'user.firstname' => ['required', 'string', 'max:255'],
            'user.lastname' => ['required', 'string', 'max:255'],
            'user.email' => ['required', 'email', 'unique:users,email,'.$id],
            'personal.additional_emails.*' => ['nullable', 'email', 'max:50'],
            'personal.additional_phones.*' => ['nullable', 'regex:/^\+?\d+$/', 'min:7', 'max:15'], 
            'personal.nationality_code' => ['required', 'string', 'size:2'],
            'personal.marital' => ['required', 'string', 'max:15'],
            'personal.new_ic' => ['required', 'string', 'size:14'],
            'personal.passport' => ['nullable', 'string'],
            'personal.hand_tel' => ['required', 'regex:/^\+?\d+$/', 'min:7', 'max:15'], // allow + symbol at front
            'personal.dob' => ['required', 'date'],
            'personal.gender' => ['required'],
            'personal.race' => ['required'],
            'interviewerNotes.who_rec_text' => ['required_if:interviewerNotes.who_rec,others']
        ];
        return $rules;
    }

    public function messages(){
        $messages = [
            'personal.hand_tel.regex' => 'The :attribute format is invalid (format: +601212345678).',
            'personal.additional_phones.*.regex' => 'The :attribute format is invalid (format: +601212345678).',
            'interviewerNotes.who_rec_text.required_if' => 'Please provide the anwswer on how did you hear about us.',
        ];
        return $messages;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        $attributes = [
            'user.firstname' => 'firstname',
            'user.lastname' => 'lastname',
            'user.email' => 'email',
            'personal.additional_emails.*' => 'email',
            'personal.additional_phones.*' => 'phone',
            'personal.nationality_code' => 'nationality',
            'personal.marital' => 'marital',
            'personal.new_ic' => 'NRIC',
            'personal.passport' => 'passport',
            'personal.hand_tel' => 'phone',
            'personal.dob' => 'date of birth',
            'personal.gender' => 'gender',
            'personal.race' => 'race',
        ];
        return $attributes;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment