Skip to content

Instantly share code, notes, and snippets.

@m5lil
Last active December 10, 2019 05:52
Show Gist options
  • Save m5lil/d58fd39fa86e6e63706fb34859ba5340 to your computer and use it in GitHub Desktop.
Save m5lil/d58fd39fa86e6e63706fb34859ba5340 to your computer and use it in GitHub Desktop.
laravel snippets,etc...
namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Multitenantable {

    protected static function bootMultitenantable()
    {

        // name convention bootXYZ() means Laravel will automatically launch this method when trait is used. You can call it a trait “constructor”.
        if (auth()->check()) {
            static::creating(function ($model) {
                $model->created_by_user_id = auth()->id();
            });

            // We’ve included Eloquent/Builder class here, and then used static::addGlobalScope() to filter any query with current logged in user. except admin
            if (auth()->user()->role_id != 1) {
                static::addGlobalScope('created_by_user_id', function (Builder $builder) {
                    $builder->where('created_by_user_id', auth()->id());
                });
            }
        }
    }

}
view()->composer('*', function (View $view) {
    //logic goes here
});
public function handle($request, Closure $next)
{
    URL::defaults(['locale' => $request->user()->locale]);

    return $next($request);
}
protected $touches = ['blog'];
// helpful to update the parent’s timestamp when the child is updated
public function blog()
{
    return $this->belongsTo(App\Blog::class);
}
$appends = [
    'full_name',
    'blogs:id,title'
];
public function blogs() {
    return $this->hasMany(App\Blog::class);
}
    public function scopePopular($query)
    {
        return $query->where('votes', '>', 100);
    }
    // User::popular()->get()
$user = User::first();
$user->name = "Peter";
$user->phone->number = '1234567890';
$user->push(); // This will update both user and phone record in DB
// Clone a model
$user = App\User::find(1);
$newUser = $user->replicate();$newUser->save();
$inUsa = collect($hosts)
    ->where('location', 'USA')
    ->when(request('retired'), function($collection) {
        return $collection->reject(function($employee){
            return $employee['is_active'];
        });
    });

@includeWhen($post->hasComments(), 'posts.comments'); $article->increment('read_count');

https://github.com/alexeymezenin/laravel-best-practices

In Laravel, instead of adding the service provider in the config/app.php file, you can add the following code to your app/Providers/AppServiceProvider.php file, within the register() method:

public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

To avoid effecting with laravel Redirctcon for subfolders in .htaccess

  # Avoid laravel RewriteCond for Chat folder
  RewriteCond %{REQUEST_URI} "/chat/"
  RewriteRule (.*) $1 [L]
  
  # Laravel RewriteCond
  RewriteRule ^(.*)/$ /$1 [L,R=301]
  
  # make Public folder as a root
  <IfModule mod_rewrite.c>
      RewriteEngine on
      RewriteCond %{REQUEST_URI} !^public
      RewriteRule ^(.*)$ public/$1 [L]
  </IfModule>
  
<IfModule mod_suphp.c>
suPHP_ConfigPath /home/website
</IfModule>

<Files php.ini>
order allow,deny
deny from all
</Files>

#Assign PHP version
<IfModule mod_suphp.c>
AddType application/x-httpd-php56 .php5 .php4 .php .php3 .php2 .phtml
suPHP_ConfigPath /usr/local/lib/php56.ini
</IfModule>


Merge two eloquent and sort them

$msgs = $msgs_from->merge($msg_to)->sortByDesc('created_at');

get only active row in database

class Model extends Model{    
    public function newQuery()
    {
        return parent::newQuery()->where('statue', '!=', 0);
    }
    // Now your Model::all() will only output your news with status = 1.
}

Fake data

$factory->define(App\Product::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->sentence(),
        'image' => 'http://loremflickr.com/400/300?random='.rand(1, 100),
        'price' => $faker->numberBetween(3, 100),
        'description' => $faker->paragraph(2)
    ];
});

in boot()

        /*
         * Set the session variable for whether or not the app is using RTL support
         * For use in the blade directive in BladeServiceProvider
         */
        if (! app()->runningInConsole()) {
            if (config('locale.languages')[config('app.locale')][2]) {
                session(['lang-rtl' => true]);
            } else {
                session()->forget('lang-rtl');
            }
        }

        Blade::if('langrtl', function ($session_identifier = 'lang-rtl') {
            return session()->has($session_identifier);
        });
namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Multitenantable {

    public static function bootMultitenantable() {
        if (auth()->check()) {
            static::creating(function ($model) {
                $model->created_by_user_id = auth()->id();
            });
            static::addGlobalScope('created_by_user_id', function (Builder $builder) {
                if (auth()->check()) {
                    return $builder->where('created_by_user_id', auth()->id());
                }
            });
        }
    }

}
@m5lil
Copy link
Author

m5lil commented Dec 10, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment