LoginSignup
0
0

More than 3 years have passed since last update.

LaravelにてDBから取得した画像をツイートする方法

Posted at

はじめに

今回は認証済みでアクセス情報も取得している前提で進めますので、
まだの方は先にそちらを完了させて下さい!

php.7.0
Laravel 7

本文

 composer require abraham/twitteroauth //twitteroauthをインストール
TweetController.php
 use Abraham\TwitterOAuth\TwitterOAuth;//先程インストールしたのをuse
 public function index(Request $request)
    {
        $api_key = //apiキーをセット;
        $secret_Key = //シークレットキーをセット;
        $access_token = //アクセストークンをセット;
        $access_token_secret = //アクセストークンシークレットをセット;

        //インスタンスを作成
        $twitter = new TwitterOAuth($api_key, $secret_Key, $access_token, $access_token_secret);

        //ここは適宜画像を取得してください
        $user = App\Models\User::inRandomOrder()->first();

        //画像の内容を読み込む
        $post_image = file_get_contents($user->image_path);

        //ローカルの画像フォルダまでのパスを指定し、そこにtweet.jpgという名前で先程読み込んだ画像をセット
        file_put_contents(public_path() . "/images/tweet.jpg", $post_image, FILE_APPEND);

        //画像をアップロード
        $user_image = $twitter->upload('media/upload', ['media' => public_path() . "/images/tweet.jpg"]);

        $twitter->post("statuses/update", [
            //ツイート本文
            "status" =>
                $user->name . PHP_EOL .
                $user->text . PHP_EOL .
                '#ハッシュタグも指定できる'. PHP_EOL,

            'media_ids' => implode(',', [
                $user_image->media_id_string
            ])
        ]);
    }

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0