Laravel queue dispatch() function forgot/not deliver values - laravel

I am trying to dispatch some files to my queue.
The dispatch() function is not working all around my stuff - for Example:
$auth = Auth::user();
$name = $request->file('file')->getClientOriginalName();
just give me a null, when DD($...); ?!
$userid = User::find(1); (by hitting the users id..) works fine!
can someone explain why that dispatch() function is not working for me?
the job code:
`
class File_Upload implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $directory;
protected $uploadDataName;
protected $inputFormName;
protected $request;
public function __construct( $directory, $uploadDataName, $inputFormName )
{
//$this->$request = $request;
$this->directory = $directory;
$this->uploadDataName = $uploadDataName;
$this->inputFormName = $inputFormName;
}
$request, $directory, $uploadDataName, $inputFormName
public function handle()
{
//vars
$request = new Request;
dd($request->file());
$name = $this->request->file($this->inputFormName)->getClientOriginalName(); // 'file' z.B
$validate = Validator::make($this->request->all(),
[
$this->inputFormName => "required|max:1000"
] );
if ( $validate->fails() )
{
return response()->json('file.prop.error'); // JSON response!
}
// get client-data Name
if ($name !== $this->uploadDataName)
{
return response()->json('file.name.error'); // JSON response!
}
$this->request->file($this->inputFormName)->storeAs($this->directory, $name) ;
//event(new Event_Data_Upload_successfull( SupportController::getAuthUser(), $uploadDataName, $directory ) );
}
The Controller...
dispatch( new File_Upload('name', 'name.csv', 'file') );
return redirect('/');
In SYNC mode that code works 100% fine.

Related

Laravel paginate

The model works well. The controller works well. The only place I'm having an error is in the view.
class Course extends Model
{
use SoftDeletes, FilterByUser;
protected $fillable = ['title', 'description', 'course_image', 'start_date', 'active', 'mandatory', 'created_by_id'];
protected $hidden = [];
public static $searchable = [
'title',
'description',
];
public static function boot()
{
parent::boot();
Course::observe(new \App\Observers\UserActionsObserver);
}
/**
* Set attribute to date format
* #param $input
*/
public function setStartDateAttribute($input)
{
if ($input != null && $input != '') {
$this->attributes['start_date'] = Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
} else {
$this->attributes['start_date'] = null;
}
}
/**
* Get attribute from date format
* #param $input
*
* #return string
*/
public function getStartDateAttribute($input)
{
$zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format'));
if ($input != $zeroDate && $input != null) {
return Carbon::createFromFormat('Y-m-d', $input)->format(config('app.date_format'));
} else {
return '';
}
}
/**
* Set to null if empty
* #param $input
*/
public function setCreatedByIdAttribute($input)
{
$this->attributes['created_by_id'] = $input ? $input : null;
}
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
public function trainers()
{
return $this->belongsToMany(User::class, 'course_user');
}
public function lessons()
{
return $this->hasMany('\App\Lesson');
}
}
I seem to have an issue with pagination. Here is the code I have for the controller and that works well.
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Here is what I have for the view:
{{$course->links()}}
this is where I get an error Call to undefined method App\Course::link()
Does anyone know what I'm doing wrong?
The Controller Code :
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Here is for the view:
#foreach($course as $row)
//Whatever you wanted to display will be written here
#endforeach
{!! $course->render() !!}
OR
#foreach($course as $row)
//Whatever you wanted to display will be written here
#endforeach
{{$course->links()}
The Controller code is fine.
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Now let's take a look at view.
#foreach($course as $row)
//Whatever action you wanted to do will be written here
#endforeach
{{$course->links()}} //The name should be differ than the name we used inside the foreach loop.

laravel 5.4 : Image file not uploaded on the aws server

When i work on locally upload image on folder works perfect but when i try to upload image on amazon web server file not uploaded and back with same page.Is there any problem with my code ?
Here is my controller function to save data :
// CountryController
public function save(Request $request) {
try {
$file = $request->file('flag_image');
$this->validate($request, Country::rules());
//$request->validate(Country::rules());
/*Image Upload code*/
If(Input::hasFile('flag_image')){
$file = Input::file('flag_image');
$destinationPath = public_path(). '/images/admin/country/';
$filename = $file->getClientOriginalName();
$image = time().$filename;
$file->move($destinationPath, $image);
$imgpath = 'images/admin/country/'.$image;
}
if($file !="") {
$request->merge(['flag_image' => $imgpath]);
}
/*Image Upload code end*/
$country = Country::saveOrUpdate($request);
if($file !="") {
$country->flag_image = $imgpath;
$country->save();
}
if($country !== false) {
return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!'));
} else {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
}
And my model code look like:
//country model
namespace App;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
class Country extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'title',
'short_name',
'flag_image',
'status'
];
const STATUSES = [
'Active' => 'Active',
'Inactive' => 'Inactive',
];
const DEFAULT_STATUS = 'Active';
/**
* Indicates if the model should be timestamped.
*
* #var bool
*/
public $timestamps = false;
public static function rules() {
return [
'title' => 'required|string|max:255',
'short_name' => 'required',
'status' => 'required|string|in:' . implode(",", Country::STATUSES)
];
}
public static function saveOrUpdate(Request $request) {
try {
$id = $request->get('id', false);
$country = false;
DB::transaction(function () use ($request, &$country, $id) {
$country = $id ? Country::findOrFail($id) : new Country();
$country->fill($request->all());
try {
$country->save();
} catch (\Exception $ex) {
throw $ex;
}
});
return $country;
} catch (\Exception $ex) {
throw $ex;
}
} }
What's the problem i didn't find anything.

Custom Laravel Passport Check

Is There anyway to add or pass 1 more variable to findForPassport ?
In default laravel passport login, i only can pass 2 variable (username, password),but I want to pass 1 more variable and check in findForPassport if that user is belong other table or not .
From the link to passport issue #81 pointed by #Arun in OP:
There's probably a better way of doing this now but I extended the PassportServiceProvider and copied the registerAuthorizationServer function so that I could register my own grant type.
Swap out the provider in config\app.php with your new one:
'providers' => [
//Laravel\Passport\PassportServiceProvider::class,
App\Providers\PassportClientCredentialsServiceProvider::class,
Updated registerAuthorizationServer function that includes new grant option:
protected function registerAuthorizationServer()
{
parent::registerAuthorizationServer();
$this->app->singleton(AuthorizationServer::class, function () {
return tap($this->makeAuthorizationServer(), function ($server) {
/**
* #var $server AuthorizationServer
*/
$server->enableGrantType(
new ClientCredentialsGrant(), Passport::tokensExpireIn()
);
/** custom grant type */
$server->enableGrantType(
new PasswordOverrideGrant(
$this->app->make(UserRepository::class),
$this->app->make(RefreshTokenRepository::class)
), Passport::tokensExpireIn()
);
$server->enableGrantType(
$this->makeAuthCodeGrant(), Passport::tokensExpireIn()
);
$server->enableGrantType(
$this->makeRefreshTokenGrant(), Passport::tokensExpireIn()
);
$server->enableGrantType(
$this->makePasswordGrant(), Passport::tokensExpireIn()
);
$server->enableGrantType(
new PersonalAccessGrant(), new \DateInterval('P1Y')
);
});
});
}
PasswordOverrideGrant looks like this:
<?php
namespace App\Auth;
use App\User;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\PasswordGrant;
use League\OAuth2\Server\RequestEvent;
use Psr\Http\Message\ServerRequestInterface;
class PasswordOverrideGrant extends PasswordGrant
{
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
{
$username = $this->getRequestParameter('username', $request);
if (is_null($username)) {
throw OAuthServerException::invalidRequest('username');
}
$custom_hash_token = $this->getRequestParameter('hash_token', $request);
if (is_null($custom_hash_token)) {
throw OAuthServerException::invalidRequest('identifier');
}
$credentials = [
'username' => $username,
'hash_token' => $custom_hash_token,
];
$user = User::where($credentials)->first();
if ($user instanceof User === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidCredentials();
}
return $user;
}
public function getIdentifier()
{
return 'password_override';
}
}
I hope this answer can help to other.
If you want to add variable and pass this variable to findPassport function in User Authenticate model , you need to update 3 class in passport :
- UserRepositoryInterface in vendor\league\oauth2-server\src\Repositories\UserRepositoryInterface
- PasswordGrant in vendor\league\oauth2-server\src\Grant\PasswordGrant
- UserRepository in vendor\laravel\passport\src\Bridge\UserRepository
in the example code I will add parent variable and code will look like this
+in UserRepositoryInterface class
interface UserRepositoryInterface extends RepositoryInterface
{
/**
* Get a user entity.
*
* #param string $username
* #param string $password
* #param string $grantType The grant type used
* #param ClientEntityInterface $clientEntity
*
* #return UserEntityInterface
*/
public function getUserEntityByUserCredentials(
$username,
$password,
$parent, <------variable example
$grantType,
ClientEntityInterface $clientEntity
);
}
+in PasswordGrant class
class PasswordGrant extends AbstractGrant{
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
{
$username = $this->getRequestParameter('username', $request);
if (is_null($username)) {
throw OAuthServerException::invalidRequest('username');
}
$password = $this->getRequestParameter('password', $request);
if (is_null($password)) {
throw OAuthServerException::invalidRequest('password');
}
/**
* Get a user parent.
* varaible example
*/
$parent = $this->getRequestParameter('parent', $request);
if (is_null($parent)) {
throw OAuthServerException::invalidRequest('password');
}
$user = $this->userRepository->getUserEntityByUserCredentials(
$username,
$password,
$parent, <--- variable example get from request
$this->getIdentifier(),
$client
);
if ($user instanceof UserEntityInterface === false) {
$this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));
throw OAuthServerException::invalidCredentials();
}
return $user;
} }
+in UserRepository class
class UserRepository implements UserRepositoryInterface
{
public function getUserEntityByUserCredentials($username, $password, $parent, $grantType, ClientEntityInterface $clientEntity)
/*add 1more parameter that implement from UserRepositoryInterface*/
{
$provider = config('auth.guards.api.provider');
if (is_null($model = config('auth.providers.'.$provider.'.model'))) {
throw new RuntimeException('Unable to determine authentication model from configuration.');
}
if (method_exists($model, 'findForPassport')) {
$user = (new $model)->findForPassport($username,$parent); <--- finally we pass parent variable to findForPassport here
} else {
$user = (new $model)->where('email', $username)->first();
}
if (! $user) {
return;
} elseif (method_exists($user, 'validateForPassportPasswordGrant')) {
if (! $user->validateForPassportPasswordGrant($password)) {
return;
}
} elseif (! $this->hasher->check($password, $user->getAuthPassword())) {
return;
}
return new User($user->getAuthIdentifier());
}
}
then u can get $parent value from parameter in findForPassport .but make sure you return value as eloquent User .if you want to join table , you can look my example code below
class User extends Authenticatable{
..........
public function findForPassport($identifier,$parent) {
$a = $this
->Join('role as r', 'r.user_id', '=', 'users.id')
->get();
return $a->where('name', $identifier)->where('role_id',$parent)->first();
}
}

Serialization of 'Closure' is not allowed laravel Queue

I am scraping a site a get some of the data and it's a time taking job so I googled and found that Queue is good for this process I am stucked in this error
Serialization of 'Closure' is not allowed
My code:
class SiteScraper extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
protected $client;
protected $crawler;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct()
{
$this->client = new Client();
$this->crawler = $this->client->request('GET', 'example.com/login/');
$form = $this->crawler->selectButton('Log In')->form();
$this->crawler = $this->client->submit($form, array('email' => 'useremail', 'pass' => 'pass'));
$this->crawler->filter('.flash-error')->each(function ($node) {
print $node->text() . "\n";
});
}
public function handle()
{
$crawler = $this->client->request('GET', $url_to_traverse);
$status_code = $this->client->getResponse()->getStatus();
if($status_code == 200){
$crawler->filter('.friendBrowserNameTitle > a')->each(function ($node) {
$names = $node->text() . '<br>';
$profileurl = $node->attr('href') . '<br>';
echo "Name : " . $names . " Profile Link : " . $profileurl;
});
}
else{
echo $status_code;
}
}
}
Any help where I am going wrong?
Only Eloquent models will be gracefully serialized and unserialized when the job is processing (Source)
So I guess that in your case, you have to write your current construct code into handle() method
class SiteScraper extends Job implements ShouldQueue
{
use InteractsWithQueue, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct(){ }
public function handle()
{
$client = new Client();
$crawler = $client->request('GET', 'example.com/login/');
$form = $crawler->selectButton('Log In')->form();
$crawler = $client->submit($form, array('email' => 'useremail', 'pass' => 'pass'));
$crawler->filter('.flash-error')->each(function ($node) {
print $node->text() . "\n";
});
$crawler = $client->request('GET', $url_to_traverse);
$status_code = $client->getResponse()->getStatus();
if($status_code == 200){
$crawler->filter('.friendBrowserNameTitle > a')->each(function ($node) {
$names = $node->text() . '<br>';
$profileurl = $node->attr('href') . '<br>';
echo "Name : " . $names . " Profile Link : " . $profileurl;
});
}
else{
echo $status_code;
}
}
}

Laravel 5.1 access event object in listener

I am trying out Laravel 5.1's queue, I am having a problem working with $event object in its listener.
AuthController.php
public function postGenerateResetToken()
{
try
{
$admin = Admin::where( 'email', '=', Input::get( 'email' ) )->firstOrFail();
$token = Bus::dispatch( new GeneratePasswordResetToken( $admin ) );
event( new PasswordResetTokenWasGenerated( $admin, $token ) );
return success();
}
catch( ModelNotFoundException $exception )
{
return fail();
}
}
PasswordResetTokenWasGenerated.php
class PasswordResetTokenWasGenerated extends Event
{
use SerializesModels;
public function __construct( $admin, $token )
{
$this->admin = $admin;
$this->token = $token;
}
public function broadcastOn()
{
return [];
}
}
SendForgottenPasswordEmail.php
class SendForgottenPasswordEmail implements ShouldQueue
{
public function __construct()
{
//
}
public function handle(PasswordResetTokenWasGenerated $event)
{
$data = [
'admin' => $event->admin,
'token' => $event->token
];
Mail::send( 'emails.forgotten-password', $data, function( $message ) use ( $event )
{
$message->subject( 'Forgotten password' );
$message->to( $event->admin->email );
});
}
}
Using $event->admin in handler results in Undefined property: PasswordResetTokenWasGenerated::$admin
But, this error only occurs when I implement ShouldQueue interface on Listener. It works just fine without the interface.
The queue driver is set to sync.
I know this is because of the queue, but isn't it supposed to work the way I want it to work?
You should declare your admin and token as public before setting them:
class PasswordResetTokenWasGenerated extends Event
{
use SerializesModels;
public $admin;
public $token;
public function __construct( $admin, $token )
{
$this->admin = $admin;
$this->token = $token;
}
public function broadcastOn()
{
return [];
}
}
After that you should be able to access those properties in your Listener.

Resources