Laravel telegram bot sdk - laravel

I have test command and I want to call or sent request this command inside my controller, pls help me!

You can call the PHP artisan command inside your controller using the following way.
use Illuminate\Support\Facades\Artisan;
$project = TelegramBaza::select('name')->where('chat_id', $chatId)->first();
if($project && $project->name == 'ANORHOME'){
//Call artisan command
$exitCode = Artisan::call('message:send', [
'user' => $user, '--queue' => 'default'
]);
}
Documentation

Related

Why I receive "CSRF token mismatch" while running tests in laravel?

I want to run my tests without receiving "CSRF token mismatch" exceptions. In the laravel documentation is noted that:
The CSRF middleware is automatically disabled when running tests.
the line of code where the exception is thrown looks like this:
$response = $this->json('POST', route('order.create'), [
'product_id', $product->id
]);
and for running tests I am working in my zsh terminal:
php artisan test --env=testing
This is my test class:
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Tests\TestCase;
class SessionCartTest extends TestCase
{
public function testExample()
{
$product = \App\Product::inRandomOrder()->first();
$response = $this->postJson(route('order.insert'), [
'product_id' => $product->id,
]);
$response->assertStatus(200); // here I receive 419
}
}
What am I doing wrong and how could I fix this? I am using laravel 7.
I ran into this problem x times now and each time I fix it by running:
php artisan config:clear
Probably the APP_ENV is not being set to testing.
You can set a ENV variable in the command line by preceding the php command.
So on your case set the environment to testing and run the artisan command by:
APP_ENV=testing php artisan test
Your data array is wrong. Try the following change:
$response = $this->postJson(route('order.insert'), [
'product_id' => $product->id, // use the arrow notation here.
]);
When you are running tests on Docker where the APP_ENV is hard coded with other values than testing (dev, local) in docker-compose.yaml file, phpunit cannot execute tests properly.
You will need to delete the all APP_ENV in docker files.
This works by setting a custom csrf-token
$this
->withSession(['_token' => 'bzz'])
->postJson('/url', ['_token' => 'bzz', 'other' => 'data']);

Lumen job dispatching done without database Queue Driver

What do I have:
Lumen service which processing particular Job
Laravel portal which sending file to that service for processing by it
Once it was using only JS and Ajax it worked almost fine - the only what I had to implement is CORS middleware. However after I moved logic to JWT (using jwt-auth package) and GuzzleHttp (I'm using it to send requests to service API) Job stopped processing throught database queue instead it running as if Queue driver being set to sync.
Following is controller which I'm calling during API call:
public function processPackageById(Request $request) {
$id = $request->package_id;
$package = FilePackage::where('id', '=', $id)->where('package_status_id', '=', 1)->first();
if($package) {
Queue::push(new PackageProcessingJob(
$this->firm,
$this->accounts,
$package
));
return 'dispatching done for ' . $id;
}
return 'dispatching not done for ' . $id;
}
where $this->firm and $this->accounts are injected Repositories for particular models. FilePackage object being created on Laravel site and both shares same database to work with.
As result no job being incerted into jobs table. When I use Postman everything is fine. However when I'm trying to send request from Laravel backend:
public function uploaderPost(Request $request)
{
// Here we get auth token and put into protected valiable `$this->token`
$this->authorizeApi();
$requestData = $request->except('_token');
$package = $requestData['file'];
$uploadPackageRequest =
$this->client->request('POST', config('bulk_api.url') .'/api/bulk/upload?token=' . $this->token,
[
'multipart' => [
[
'name' => 'file',
'contents' => fopen($package->getPathName(), 'r'),
'filename' => $package->getClientOriginalName(),
],
]
]);
$uploadPackageRequestJson = json_decode($uploadPackageRequest->getBody()->getContents());
$uploadPackageRequestStatus = $uploadPackageRequestJson->status;
if($uploadPackageRequestStatus == 1) {
$package = BulkUploadPackage::where('id', '=',$uploadPackageRequestJson->id)->first();
// If package is okay - running it
if($package !== null){
// Here where I expect job to be dispatched (code above)
$runPackageRequest =
$this->client->request('POST', config('api.url') .'/api/bulk/run?token=' . $this->token,
[
'multipart' => [
[
'name' => 'package_id',
'contents' => $package->id
],
]
]);
// Here I'm receiving stream for some reason
dd($runPackageRequest->getBody());
if($runPackageRequest->getStatusCode()==200){
return redirect(url('/success'));
}
}
}
return back();
}
Could anyone advise me what is wrong here and what causes the issue?
Thank you!
Alright, it was really interesting. After echoing config('queue.default') in my contoller it appeared that it's value indeed sync nevertheless that I set everything correctly.
Then I assumed that maybe the reason in Laravel itself and its variables. Indeed in .env file from Laravel side QUEUE_DRIVER being set to sync. After I changed it to QUEUE_DRIVER=database everything started working as expected.
Hope that will help someone in future.

Method Illuminate\Auth\SessionGuard::users does not exist

I'm having a problem with Auth. I'm just learning about Laravel, I'm doing login. I don't know how to fix it it says:
Method Illuminate\Auth\SessionGuard::users does not exist.
this is my code in login function
public function getlogin(Request $request){
$this->validate($request, [
'email'=> 'required|max:32',
'password'=> 'required|max:32|min:8',
]);
if (Auth::attempt(['email'=>$request->email,'password'=>$request->password])) {
$user = users::where('email','=',$request->email)->first();
return redirect('/messenger')->with('usersignin');
}
return "ooopps something wrong";
}
and this is where the name from the database will be display
<div class="">
<h1>Welcome
#if(session('user'))
{{session('user')}}
#elseif(session('usersignin'))
{{ucwords(Auth::users()->fname)}}
#endif</h1>
</div>
You need to use user instead of users, user is provided with Auth and will get the current logged in user id.
$id = \Auth::user()->id;
Or you want to get the user
$user = \Auth::user();
I solved this error by running the below command
php artisan jwt:secret
php artisan cache:clear
php artisan config:cache
in your if statement just use it as below
if (auth()->attempt(['email'=>$request->email,'password'=>$request->password])) {
$user = users::where('email','=',$request->email)->first();
return redirect('/messenger')->with('usersignin');
}

Unable To Connect Laravel to MailChimp (laravel 5.4)

I have to define List ID and MailChimp API Key in my .env file. I'm sure both are fine even I am not getting any error but email in not inserting in my List I installed https://github.com/spatie/laravel-newsletter (spatie/laravel-newsletter) Package.
Here is my method
public function subscribe(Request $request)
{
$email = request('email');
Newsletter::subscribe($email);
Session::flash('subscribed', 'Successfully subscribed.');
return redirect()->back();
}
Then I check subscribe Method in Newsletter.php
it is as
public function subscribe($email, $mergeFields = [], $listName = '', $options = [])
{
$list = $this->lists->findByName($listName);
$options = $this->getSubscriptionOptions($email, $mergeFields, $options);
$response = $this->mailChimp->post("lists/{$list->getId()}/members", $options);
if (! $this->lastActionSucceeded()) {
return false;
}
return $response;
}
I print options variable it returns output as
array:3 [▼
"email_address" => "bluemoon#gmail.com"
"status" => "subscribed"
"email_type" => "html"
]
Then I print below variable $response it returns false Please Help whats wrong with this.
Thanks In advance
Not sure this will directly resolve your issue, but you need to run the following command in your terminal:
php artisan vendor:publish --provider="Spatie\Newsletter\NewsletterServiceProvider"
This creates a laravel-newsletter.php in the config directory, that's where your List ID and MailChimp API key should go.
PS: the package seems to have an issue with env so don't use it, just enter your keys as strings.

Sending a registration request to Laravel

I'm trying to send a post request to my Laravel app so that I could create a User without the UI.
I've tried sending a post request via cURL:
curl --data "name=test&password=password120918&email=app#test.com" http://localhost:8080/register
This didn't work.
This is a fresh install of Laravel 5.4
I can't find anything to do with the RegisterController in the routes/web.php file.
What would the url to register a user be for Laravel 5.4? (I'm pretty sure it works the same way as 5.3)
Thank you.
I know that in laravel there is a default way to do things, But if your just looking to create a user from post request and send it back as a response you can do it yourself.
in your routes.php
Route::post("/users", "UsersController#store");
Then create a UsersController.php and add the method:
public function store(Request $request){
//You should add validation before creating the user.
$user = App\User::create([
"email" => $request->email,
"name" => $request->name,
"password" => bcrypt($request->password)
]);
if(!$user){
return response(["error" => "Your error here"], 400);
}
return response(["user" => $user], 200);
}
Then try it our with postman or curl command like
curl -X POST -F 'name=Testing User' -F 'password=pass1234' -F 'email=testing#gmail.com' http://localhost:8080/users
php artisan route:list
Will show you all of the registered routes for your application. When using Laravel's built in auth, routes are registered without them actually being in your routes file.
By default Laravel adds a POST route for /register to
App\Http\Controllers\Auth\RegisterController#register

Resources