-1

I want to insert data to db using only something like DB::insert.
So, I have this line of code:

DB::insert("INSERT INTO `users` (`vk_id`, `name`, `email`) VALUES ($user->id, $user->name, $user->email)");

I do use use Illuminate\Support\Facades\DB;

But I have an error:

syntax error, unexpected 'DB' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

What's the cause of this error?

The whole file code

<?php

namespace SocialiteProviders\VKontakte;

use Illuminate\Support\Arr;
use Laravel\Socialite\Two\InvalidStateException;
use SocialiteProviders\Manager\OAuth2\AbstractProvider;
use SocialiteProviders\Manager\OAuth2\User;

use Illuminate\Support\Facades\DB;

class Provider extends AbstractProvider
{
    protected $fields = ['id', 'email', 'first_name', 'last_name', 'screen_name', 'photo_200'];

    /**
     * Unique Provider Identifier.
     */
    const IDENTIFIER = 'VKONTAKTE';

     /**
     * {@inheritdoc}
     */
    protected $stateless = true;

    /**
     * {@inheritdoc}
     */
    protected $scopes = ['email'];

    /**
     * Last API version.
     */
    const VERSION = '5.92';

    /**
     * {@inheritdoc}
     */
    protected function getAuthUrl($state)
    {
        return $this->buildAuthUrlFromBase(
            'https://oauth.vk.com/authorize', $state
        );
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenUrl()
    {
        return 'https://oauth.vk.com/access_token';
    }

    /**
     * {@inheritdoc}
     */
    protected function getUserByToken($token)
    {
        $from_token = [];
        if (is_array($token)) {
            $from_token["email"] = isset($token["email"]) ? $token["email"] : null;

            $token = $token["access_token"];
        }

        $params = http_build_query([
            'access_token' => $token,
            'fields'       => implode(',', $this->fields),
            'lang'     => $this->getConfig('lang', 'en'),
            'v'            => self::VERSION,
        ]);

        $response = $this->getHttpClient()->get('https://api.vk.com/method/users.get?' . $params);

        $contents = $response->getBody()->getContents();

        $response = json_decode($contents, true);

        if (!is_array($response) || !isset($response['response'][0])) {
            throw new \RuntimeException(sprintf(
                'Invalid JSON response from VK: %s',
                $contents
            ));
        }

        return array_merge($from_token, $response['response'][0]);
    }

    /**
     * {@inheritdoc}
     */
    public function user() {
        if ($this->hasInvalidState()) {
            throw new InvalidStateException;
        }

        $response = $this->getAccessTokenResponse($this->getCode());

        $user = $this->mapUserToObject($this->getUserByToken($response));

        $this->credentialsResponseBody = $response;

        if ($user instanceof User) {
            $user->setAccessTokenResponseBody($this->credentialsResponseBody);
        }

        return $user->setToken($this->parseAccessToken($response))
            ->setExpiresIn($this->parseExpiresIn($response));
    }

    /**
     * {@inheritdoc}
     */
    protected function mapUserToObject(array $user)
    {
        return (new User())->setRaw($user)->map([
            'id'       => Arr::get($user, 'id'),
            'nickname' => Arr::get($user, 'screen_name'),
            'name'     => trim(Arr::get($user, 'first_name').' '.Arr::get($user, 'last_name')),
            'email'    => Arr::get($user, 'email'),
            'avatar'   => Arr::get($user, 'photo_200'),
        ]);
    }

    /**
     * {@inheritdoc}
     */
    protected function getTokenFields($code)
    {
        return array_merge(parent::getTokenFields($code), [
            'grant_type' => 'authorization_code',
        ]);
    }

    /**
     * Set the user fields to request from Vkontakte.
     *
     * @param array $fields
     *
     * @return $this
     */
    public function fields(array $fields)
    {
        $this->fields = $fields;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public static function additionalConfigKeys()
    {
        return ['lang'];
    }

    DB::insert('insert into users (vk_id, name, email) values (?, ?, ?)', [
        $user->id, $user->name, $user->email
    ]);
}
inrate
  • 355
  • 2
  • 15

1 Answers1

0

According to the comments, you can not put your statements directly in the class construction, instead you have to put it inside a function or the constructor of the class.

But also note that:

Raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.

So it's better to use this statement instead, because parameter binding provides protection against SQL injection.:

use Illuminate\Support\Facades\DB;

DB::insert('insert into users (vk_id, name, email) values (?, ?, ?)', [
    $user->id, $user->name, $user->email
]);

Or simply:

use Illuminate\Support\Facades\DB;

DB::table('users')->insert([
    'vk_id' => $user->id,
    'email' => $user->email,
    'name' => $user->name
]);
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63