Clear Cach, Loading Old Version Of Class

composer clear-cache
composer dump-autoload
Advertisements

Laravel DB Transaction Not Working

‘mysql’ => [
‘driver’ => ‘mysql’,
‘host’ => env(‘DB_HOST’, ‘127.0.0.1’),
‘port’ => env(‘DB_PORT’, ‘3306’),
‘database’ => env(‘DB_DATABASE’, ‘amazon-gift-card’),
‘username’ => env(‘DB_USERNAME’, ‘root’),
‘password’ => env(‘DB_PASSWORD’, ”),
‘unix_socket’ => env(‘DB_SOCKET’, ”),
‘charset’ => ‘utf8mb4’,
‘collation’ => ‘utf8mb4_unicode_ci’,
‘prefix’ => ”,
‘strict’ => false,
‘engine’ => ‘InnoDB’, // chagne this before create table or migration table
],

Accesss Store Procedure

$GeneralSearch = ”;
$DepartmentID = 0;
$CategoryID = 0;
$Brands = ”;
$Instock = 0;
$PriceLevel = 0;
$MinPrice = 0;
$MaxPrice = 500;
$Sort = 0;

$db = DB::connection()->getPdo();
$stmt = $db->prepare(“EXEC [dbo].[SP_Web_Search] ?,?,?,?,?,?,?,?,?”);
$stmt->bindParam(1, $GeneralSearch);
$stmt->bindParam(2, $DepartmentID);
$stmt->bindParam(3, $CategoryID);
$stmt->bindParam(4, $Brands);
$stmt->bindParam(5, $Instock);
$stmt->bindParam(6, $PriceLevel);
$stmt->bindParam(7, $MinPrice);
$stmt->bindParam(8, $MaxPrice);
$stmt->bindParam(9, $Sort);
$stmt->execute();
$result = $stmt->fetchAll();

Select CONCATE COLUMNS

$items = Item::join(‘Department’,’Item.DepartmentID’,’=’,’Department.ID’)
->select(DB::raw(‘CONCAT(Item.Name, Department.Name) as user_count’))
->where([‘Item.Active’=>1,’Item.WebsiteShow’=>1])->get();

Social Facebook Login

Reference URL: https://github.com/SammyK/LaravelFacebookSdk#installation

Route::get(‘/facebook/login’, function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
// Send an array of permissions to request
$login_url = $fb->getLoginUrl([’email’]);

// Obviously you’d do this in blade đŸ™‚
echo ‘Login with Facebook‘;
});

// Endpoint that is redirected to after an authentication attempt
Route::get(‘/facebook/callback’, function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb)
{
// Obtain an access token.
try {
$token = $fb->getAccessTokenFromRedirect();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}

// Access token will be null if the user denied the request
// or if someone just hit this URL outside of the OAuth flow.
if (! $token) {
// Get the redirect helper
$helper = $fb->getRedirectLoginHelper();

if (! $helper->getError()) {
abort(403, ‘Unauthorized action.’);
}

// User denied the request
dd(
$helper->getError(),
$helper->getErrorCode(),
$helper->getErrorReason(),
$helper->getErrorDescription()
);
}

if (! $token->isLongLived()) {
// OAuth 2.0 client handler
$oauth_client = $fb->getOAuth2Client();

// Extend the access token.
try {
$token = $oauth_client->getLongLivedAccessToken($token);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}

$fb->setDefaultAccessToken($token);

// Save for later
Session::put(‘fb_user_access_token’, (string) $token);

// Get basic info on the user from Facebook.
try {
$response = $fb->get(‘/me?fields=id,name,email’);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}

// Convert the response to a `Facebook/GraphNodes/GraphUser` collection
$facebook_user = $response->getGraphUser();

// Create the user if it does not exist or update the existing entry.
// This will only work if you’ve added the SyncableGraphNodeTrait to your User model.
print_r($facebook_user);exit();
$user = App\User::createOrUpdateGraphNode($facebook_user);

// Log the user into Laravel
Auth::login($user);

return redirect(‘/’)->with(‘message’, ‘Successfully logged in with Facebook’);
});

https://mattstauffer.co/blog/introducing-mailables-in-laravel-5-3

Introducing Mailables in Laravel 5.3

(This is part of a series of posts on New Features in Laravel 5.3.)

  1. Introducing Laravel Echo: An In-Depth Walk-Through
  2. The new $loop variable in Laravel 5.3
  3. Customizing additional parameters in FirstOrCreate in Laravel 5.3
  4. The new cache() global helper in Laravel 5.3
  5. New JSON-column where() and update() syntax in Laravel 5.3
  6. Advanced operations with Collection::where in Laravel 5.3
  7. Image dimension validation rules in Laravel 5.3
  8. Customizing pagination templates in Laravel 5.3
  9. 5.3 feature announcement notes from Laracon
  10. Routing changes in Laravel 5.3
  11. Introducing Laravel Scout
  12. Introducing Laravel Passport
  13. Introducing Mailables in Laravel 5.3
  14. Directory structure changes in Laravel 5.3
  15. The new Notification system in Laravel 5.3
  16. Update to queue workers in Laravel 5.3
  17. Using Vue in Laravel 5.3, with the Vue bootstrap and sample component
  18. Defining console commands via closure in Laravel 5.3

For the longest time, sending mail in Laravel has felt clumsy compared to the relatively light APIs of most other Laravel features. Here’s a mail example from the Laravel 5.2 docs:

Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('', 'Your Application');

    $m->to($user->email, $user->name)->subject('Your Reminder!');
});

I’m not saying it’s awful—it’s still so much cleaner than its competitors–but it’s often confusing to figure out what goes in the closure and what doesn’t, what the parameter order is, etc.

Introducing Mailables #

Mailables are PHP classes in Laravel 5.3 that represent a single email: “NewUserWelcome”, or “PaymentReceipt”. Now, similar to event and job dispatching, there’s a simple “send” syntax, to which you’ll pass an instance of the class that represents what you’re “dispatching”; in this context, it’s an email.

So now, that email above looks like this:

Mail::to($user)->send(new Reminder);

Let’s take a look at that Reminder class. First, create it with an Artisan command:

php artisan make:mail Reminder

It’ll now live in app/Mail directory. Let’s take a look at how it looks out of the box:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class Reminder extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('view.name');
    }
}

All of the configuration you’re used to doing in closures now takes place in the build() method. So let’s re-create that example email again:

public function build()
{
    return $this->from('', 'Your Application')
        ->subject('Your Reminder!')
        ->view('emails.reminder');
}

Note: If you don’t explicitly set the subject, Laravel will guess it from your class name. So if the class is named “ApplicationReminder”, the default subject will be “Application Reminder”.

Passing data #

Now, what if we want to pass some data in to the subject or into the view? That goes into the constructor:

Mail::to($user)->send(new Reminder($event));
class Reminder extends Mailable
{
    public $event;

    public function __construct($event)
    {
        $this->event = $event;
    }

    public function build()
    {
        return $this->from('', 'Your Application')
            ->subject('Event Reminder: ' . $this->event->name)
            ->view('emails.reminder');
    }
}

Any public properties on our mailable class will be made available to the view, so we can now use $event in the view:

// resources/views/emails/reminder.blade.php
<h1>{{ $event->name }} is coming up soon!</h1>
<p>Lorem ipsum.</p>

But what if you’d prefer specifying the data explicitly? You can do that—pass an array to a with() call in build():

public function build()
{
    return $this->from('', 'Your Application')
        ->subject('Event Reminder: ' . $this->event->name)
        ->view('emails.reminder')
        ->with(['title' => $this->event->name]);
}

Customizing the delivery list #

As you can see, customizing the email itself happens in the build() method and customizing who’s getting it happens when we call the email. Let’s take a look at cc and bcc:

Mail::to(User::find(1))
    ->cc(User::find(2))
    ->bcc(User::find(3))
    ->send(new Reminder);

// These methods also accept collections
Mail::to(Users::all())
    ->send(new Reminder);

Plaintext views #

There’s a new text() method to go along with the new view() method. You can pass it the view you want used for the plaintext version of this email:

public function build()
{
    return $this->view('emails.reminder')
        ->text('emails.reminder_plain');
}

Queueing mailables #

One of the problems with sending mail in line with your application’s execution is that it can often take a few seconds to send. Queues are the perfect answer to this. They’re already easy with Laravel’s pre-existing mail syntax, and it stays easy here: Just run Mail::queue instead of Mail::send.

Mail::to($user)->queue(new Reminder);

You can also use later to specify when it should be sent:

$when = Carbon\Carbon::now()->addMinutes(15);

Mail::to($user)->later($when, new Reminder);

Attachments #

You’ll probably get used to hearing this. Everything you can currently run within your mail closures, you can run within the build() method. This includes attach(). The first parameter is the path to the file, and the optional second parameter takes an array for customizing the details of the attached file.

public function build()
{
    $this->view('emails.reminders')
        ->attach('/path/to/file', [
            'as' => 'name.pdf',
            'mime' => 'application/pdf',
        ]);
}

You can also use attachRaw to attach raw data:

public function build()
{
    $this->view('emails.reminders')
        ->attachRaw($this->pdf, 'name.pdf', [
            'mime' => 'application/pdf',
        ]);
}

Multiple DB Connections in Laravel

Multiple DB Connections in Laravel

A while ago, I answered on this SO question about using 2 database connections.

In answering that, I did some investigation which I’ll write up here.

Here is how to run more than one database connection.

This article is about using databases with different data, not necessary for load balancing (or connection pooling) between databases.

Define Connections

Inside of your datbase configuration file – likely app/config/database.php – you can define more than one database connection of any type. In fact, you can define as many connections as you’d like. For instance, if your application has to pull data from 2 MySQL databases, you can define them both separately:

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        # Our primary database connection
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        # Our secondary database connection
        'mysql2' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    ),
);

We have our default connection still set to mysql. This means that, unless we specify otherwise, the application will use thet mysql connection.

Specify Connection

Now that we have a 2nd database connection setup – how do we use it in code?

It turns out there’s a few ways!

Schema

Within the Schema Builder, you can use the Schema facade with any connection. To specify which connection to use, simply run the connection() method:

Schema::connection('mysql2')->create('some_table', function($table)
{
    $table->increments('id'):
});

Query

Similar to Schema Builder, you can define a connection on the Query Builder:

$users = DB::connection('mysql2')->select(...);

Eloquent

You can also define which connection to use in your Eloquent models as well!

One way is to set the $connection variable in your model:

<?php

class SomeModel extends Eloquent {

    protected $connection = 'mysql2';

}

You can also define the connection at runtime via the setConnection method.

<?php

class SomeController extends BaseController {

    public function someMethod()
    {
        $someModel = new SomeModel;

        $someModel->setConnection('mysql2');

        $something = $someModel->find(1);

        return $something;
    }

}

Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.

Create a free website or blog at WordPress.com.

Up ↑