alihoushyaripour

Experience

2,950

0 Best Reply Awards

  • Member Since 2 Months Ago
  • 0 Lessons Completed
  • 0 Favorites

17th September, 2018

alihoushyaripour started a new conversation How To Pass Array Data Instead Of Model Object To Resource Collection Class? • 4 days ago

Hi,

I have a route that do search with lucene search framework and get array data from search query. Now I need to pass array data to my resource collection class to make response data, but when the program comes to this line of code:

$userArr = User::collection($users);

show me this error:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Call to undefined method stdClass::first()

16th September, 2018

alihoushyaripour left a reply on How To Speed Up Insert Query? • 4 days ago

@Cronix

Thanks, I use your solution but nothing has been changed, insert speed is similar ago and insert data one row in every time and not bulk.

How to set to transaction how many queries to run together? for example every 1000 queries run together.

alihoushyaripour left a reply on How To Speed Up Insert Query? • 4 days ago

@Cronix

Thanks my friend.

I have relational db and in every insert I get last inserted id and use that for next insert, like this:

foreach ($items as $item) {
    // insert address
    $addressId = DB::table('address')->insertGetId([
        // parameters
    ]);

    // insert user
    $userId = DB::table('user')->insertGetId([
        // parameters
    ]);

    // insert place
    DB::table('place')->insert([
        'user_id' => $userId,
        'address_id' => $addressId,
        'name' => $item->name,
        'coordinate' => $item->coordinate,
        // other parameters
    ]);
}

Can I use bulk insert for this also?

alihoushyaripour left a reply on How To Speed Up Insert Query? • 4 days ago

@Cronix

Of course, you're right, but because my schema has been changed, I have to write simple insert queries like this for every table:

DB::table('table_name')->insert([
    // parameters
]);

What should I do?

alihoushyaripour started a new conversation How To Install And Use JIT Compiler (HHVM) In Laravel Project ? • 4 days ago

Hi,

I want to install and use hhvm on my project, but I can't found a good doc or tutorial for that.

Can anyone help me?

alihoushyaripour started a new conversation How To Speed Up Insert Query? • 4 days ago

Hi,

I have a old db and I write a code to insert it's data to a new db (row to row). In every table exist more than 1 million data, because that inserts take too long on a strong vps.

I saw if I use transaction, can speed up insert but I don't know how can I use it !? And is there exist any other way !?

My vps conf:

RAM: 2G
CPU: Core i7
OS: Centos 7
HDD: 100G
PHP: php-fpm
DB: MariaDb

11th September, 2018

alihoushyaripour left a reply on How To Get Data From Left Join As Separate Array Instead Of Parameters? • 1 week ago

@MikeRees Yes my friend, I change my database and tables schema, everything has changed! and now write a seed class to insert old db data to the new one.

alihoushyaripour left a reply on How To Get Data From Left Join As Separate Array Instead Of Parameters? • 1 week ago

@tykus No, I write my project 2 month ago with pure php and mysql, and now I want to switch to laravel framework and I need to insert my old db (in php project) to new db (in laravel project)

alihoushyaripour left a reply on How To Get Data From Left Join As Separate Array Instead Of Parameters? • 1 week ago

@tykus My tables not define in my laravel project, I write this tables ago, and now want to write it in my models and need to get those first and insert to models.

Is there any solution?

alihoushyaripour started a new conversation How To Get Data From Left Join As Separate Array Instead Of Parameters? • 1 week ago

Hi,

I need to get some data using DB::query from db, it's this:

$var = DB::table('places')
->leftJoin('phones', 'places.id', '=', 'phones.place_id')
->leftJoin('features', 'places.id', '=', 'features.place_id')
->take(1);

But response value is an object that contain all columns of these three table together and repetitive parameters replace with together. response that I want is this:

{
    "id",
    "name",
    // and other place parameters

    "phones": [
        {},
        ...
    ],

    "features": [
        {},
        ...
    ],
}

How can I make It ?!

2nd September, 2018

alihoushyaripour started a new conversation What Is Best Way To Upload Multiple Image In Restful? • 2 weeks ago

Hi,

I want to upload multiple image file in my application, I read youtube video upload rest api module that say:

  1. First send a request that contain meta info of image file like size, count, mime and so on with POST method and JSON body. (send image data)

  2. And then when received the success answer, send second request and put image file and other meta parameters as key value in form-data type. (upload image)

I was used it and be ok, but when the client wants to send multiple images in this way, I can't work with it, because there may be a problem when an image is uploading and images inserted in db incorrectly.

Is there any better way to handle upload image in restful?

27th August, 2018

alihoushyaripour left a reply on How To Recover .git Directory? • 3 weeks ago

@brightstormhq

When I push my code with:

git push -u origin master

show me this message to me:

fatal: unable to access 'https://gitlab.com/alihoushyaripour/test.git/': Failed to connect to user.email port 1080: Timed out

alihoushyaripour started a new conversation How To Recover .git Directory? • 3 weeks ago

Hi,

I pushed my code to git everyday, but yesterday .git folder of my project deleted and now I haven't it and can't get or download it again to push my new commit.

How can I recover or download it again?

26th August, 2018

alihoushyaripour started a new conversation How To Bind Model Services And Repositories In AppServiceProvider? • 3 weeks ago

Hi,

I write my laravel code like spring framework, I have App\Services\ and App\Repositories\ directory that my controllers connect to service that service is my logic layer and repository is for write eloquent and connect to db.

This is Global Schema of my every controller, service and repository :

// controller class
class TestController extends Controller
{
    private $service;

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


// service class
class TestService
{
    private $repository;

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

    // functions
}


// repository class
class TestRepository
{
    function __construct()
    {
    }

    // functions
}

Now I have a route that in it related controller call a UserService in it's __construct and in end of controller with this:

return app('App\Http\Controllers\Test2Controller')->function();

move to other controller that call UserService in it's __construct.

In other word, every of these two service use twice in one route.

Are this a problem?

I do not bind my services and repositories in AppServiceProvider and everywhere in controllers I use those in __constructor, in top of code, use it's class and do not service bind to controller.

Should I bind my services in AppServiceProvider? and How?!

alihoushyaripour left a reply on Why All Of Request With POST Method Not Work Without Any Reason? • 3 weeks ago

this error show every 10 times that I tested:

Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) {"exception":"[object] (Symfony\Component\Debug\Exception\FatalErrorException(code: 1): Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes) at C:\wamp64\www\pinjob-laravel\vendor\laravel\framework\src\Illuminate\Container\Container.php:774)

alihoushyaripour started a new conversation Why All Of Request With POST Method Not Work Without Any Reason? • 3 weeks ago

Hi,

I have many request with get and post method, but suddenly without any reason all of post request not work and occur 500 internal error without any debug result, response body is empty.

Does anyone know why?

23rd August, 2018

alihoushyaripour started a new conversation How Can I Update Just The Changes In Model? • 4 weeks ago

Hi,

I want to update a model(only properties that have changed) like user, in repository I write this:

public function update($id, $username, $firstName, $lastName)
{
    // user
    $user = new User()::find($id);

    // username
    if ($user->username !== $username) {
        $user->username = $username;
    }

    // first_name
    if ($user->first_name !== $firstName]) {
        $user->first_name = $firstName];
    }

    // last_name
    if ($user->last_name !== $lastName) {
        $user->last_name = $lastName;
    }

    // save
    $user->save();

    // success
    return true;
}

Is there any better way? this take a lot of line.

alihoushyaripour started a new conversation How To Handle Received File And Json Data Together? • 4 weeks ago

Hi,

My client(android) call a route with post that handle this with multipart library to send a request to server.

In this route need to upload image inside of json data(image and json together)

When I read Request or request()->all() or $_REQUEST I can see json parameters, but when I read File or $_FILE, I see binary data(just 0,1 and not file parameters)

What should I do? I don't like to read image as code and encode it again, I want to get file as file.

21st August, 2018

alihoushyaripour started a new conversation Is There Exist Any Way To Get Ipv6 From Client Request? • 4 weeks ago

Hi,

Is there any way to get ipv6 from a request that send from android device client?

Or must send it as parameter from android device?

alihoushyaripour left a reply on What Is Best Way To Generate Secure Token For Mobile Application Users? • 4 weeks ago

My friends, no one has any idea?

alihoushyaripour started a new conversation Why Boolean Parameters With The 'false' Value, Not Received In Request? • 4 weeks ago

Hi,

Assume I received two parameter with bool1 and 'bool2' that are boolean and 'bool1' has been initialized with true and 'bool2' with false

Now this is my log:

Array
(
    [bool1] => 1
    [bool2] => 
)

'bool2' not initialized with any value, but why?

20th August, 2018

alihoushyaripour started a new conversation How To Validate Count Of Array Objects In Request Class? • 1 month ago

Hi,

I have a request class that validate an array of categories that each one of them have an id

Now I want to check count of received categories and limited to 3, how can I check it?

Request class:

class PlaceCategory extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'categories' => 'required|array',
            'categories.id' => 'required|numeric|integer|regex:/^[0-9]+$/',
        ];
    }
}

alihoushyaripour started a new conversation What Is Best Way To Generate Secure Token For Mobile Application Users? • 1 month ago

I have a mobile application and want to generate token for every user in login time, but don't know what is the best way?

Re-generate token continuously every few days?

Logout user continuously every few days, to force him to login again?

generate a long token to and send it in POST body to be safe?

Or something else...

16th August, 2018

alihoushyaripour left a reply on How To Call A Controller Function That Has The Request Class Input? • 1 month ago

@NOMGUY

Ok, what repository should I write?

I can't pass type and id parameters value to UploadRequest class manual, my problem is this.

alihoushyaripour started a new conversation How To Call A Controller Function That Has The Request Class Input? • 1 month ago

Hi,

I have a controller with two function that I need to call upload function from add function while upload function has the UploadRequest class as input.

How can I make an instance of UploadRequest class, and call upload function?!

Controller class:

class ImageController extends Controller
{
    public function add(Request $request)
    {
        // code

        // call $this->upload()
    }

    public function upload(UploadRequest $request)
    {
        // validate
        $request = $request->validated();

        // code
    }
}

UploadRequest class:

class UploadRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'type' => 'required|string|in:avatar,place,review,meta',
            'id' => 'required|numeric|integer|regex:/^[0-9]+$/'
        ];
    }
}

15th August, 2018

alihoushyaripour left a reply on How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

@Cronix

You're right, but it will not work until I include all of the id/foreign id's completely, I don't know why...!!??

14th August, 2018

alihoushyaripour left a reply on How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

Finally I founded Solution that worked correctly:

$this->hasManyThrough(
    Category::class, 
    PlaceCategory::class, 
    'place_id', // Place foreign key in PlaceCategory class
    'id', // Place class primary key
    'id', // Category class primary key
    'category_id'// Category foreign key in PlaceCategory class
    );

alihoushyaripour left a reply on How To Get Limit Of Resource Response Array? • 1 month ago

No, I want to get a limit numbers of users from resource collection, not paginate on eloquent, because paginate add some additional parameters to response that I don't want to this happen.

Is there any other solution ?!

alihoushyaripour started a new conversation How To Get Limit Of Resource Response Array? • 1 month ago

Hi,

I have a resource class like this:

class UserResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => [
                'first' => $this->first_name,
                'last' => $this->last_name
            ]
        ];
    }
}

and in controller I write this:

$users = UserResource::collection(User::where(['is_report' => true]));

This query return 100 user, but I want to filter it to 10 user.

How can I filter or set limit to resource response class ?!

alihoushyaripour left a reply on How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

@Vilfago

My models:

// place model
class Place extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function categories()
    {
        return $this->belongsToMany(Category::class, PlaceCategory::class, 'place_id', 'category_id');
    }
}

// place category model
class PlaceCategory extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function place()
    {
        return $this->belongsTo(Place::class, 'place_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
}

// category model
class Category extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function placeCategories()
    {
        return $this->hasMany(PlaceCategory::class, 'category_id', 'id');
    }
}

My migrations:

// place migration
class Place extends Migration
{
    ...
    $table->bigIncrements('id');
    ...
}

// place category migration
class PlaceCategory extends Migration
{
    ...
    $table->bigIncrements('id');
    $table->unsignedBigInteger('place_id');
    $table->unsignedBigInteger('category_id');
    ...
}

// category migration
class Category extends Migration
{
    ...
    $table->bigIncrements('id');
    ...
}

I haven't category_place field or function in my model classes that you used in place model class, what is it ?!

alihoushyaripour left a reply on How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

@Vilfago

The code you wrote did not work my friend, response is:

{}

I check relations and data, everything be ok, but not work -_-

alihoushyaripour left a reply on How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

@Vilfago

see this:

Place hasMany PlaceCategory
Category hasMany PlaceCategory

PlaceCategory belongsToMany Place
PlaceCategory belongsToMany Category

Now I want to write a function in Place class to get it's categories, so I need a hasManyThrough :)

But I write these but none of them work:

// place model
class Place extends Model
{
    // categories
    public function categories()
    {
        // 1
        // return $this->hasManyThrough(Category::class, PlaceCategory::class);

        // 2
        // return $this->hasManyThrough(Category::class, PlaceCategory::class, 'category_id', 'place_id', 'id', 'id');

        // 3
        // return $this->hasManyThrough(PlaceCategory::class, Category::class);

        // 4
        // return $this->hasManyThrough(PlaceCategory::class, Category::class, 'place_id', 'category_id', 'id', 'id');
    }
}

13th August, 2018

alihoushyaripour left a reply on How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

@Vilfago

Yes PlaceCategory is pivot table.

Can you explain belongsToMany how to work? I tested different forms of it and not work for me.

alihoushyaripour started a new conversation How To Get Third Model, Where Three Model Have Relationed Together? • 1 month ago

Hi,

I have three models as follows:

// place model
class Place extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function places()
    {
        return $this->hasMany(PlaceCategory::class, 'place_id', 'id');
    }
}

// place category model
class PlaceCategory extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function place()
    {
        return $this->belongsTo(Place::class, 'place_id', 'id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
}

// category model
class Category extends Model
{
    /**
     * @return \Illuminate\Database\Eloquent\Relations\belongsTo
     */
    public function placeCategories()
    {
        return $this->hasMany(PlaceCategory::class, 'category_id', 'id');
    }
}

Now in 'Place' class I want to have an function with name 'categories' that get to me a relation to 'Category' class with 'hasMany' method, to use of it in 'PlaceResource' class for response.

Anyone can help me?!

alihoushyaripour left a reply on How To Addition A Column With Eloquent? • 1 month ago

@tykus

I know, My purpose wasn't to ignore your help, but he get a solution and also referenced to your solution, because that his solution be more complete, don't upset from me.

alihoushyaripour left a reply on What's Reason Of This Error? • 1 month ago

@tykus

Surelly 'null' get back.

alihoushyaripour left a reply on What's Reason Of This Error? • 1 month ago

@Vilfago

I don't know how many places founded from search.

if one data found, I should write collection like this?

// resource
$places = PlaceResource::make($result->places);

And if more than one data found:

// resource
$places = PlaceResource::collection($result->places);

Do I have to check how many data has been found from search and write response resource somehow it's suitable for resource?

alihoushyaripour started a new conversation What's Reason Of This Error? • 1 month ago

I can't describe my problem well, so take a photo:

http://s8.picofile.com/file/8334367950/Screenshot_56_.png

This error happen for a route and in every 5 times that I refresh browser, in 4 times this error occur and in 1 time response get backed successfully...

Has anyone ever encountered this problem?!

alihoushyaripour left a reply on How To Addition A Column With Eloquent? • 1 month ago

@JuanRangel

Thanks, but if I want to update this with some other rows like this:

User::find($userId)->increment('rate')->update(['active' => true, 'updated_at' => $date]);

this not work again.

alihoushyaripour started a new conversation How To Addition A Column With Eloquent? • 1 month ago

Hi,

I want to update a row by adding a column of it (similar to ++ operation)

I wrote this in two forms, but not work:

User::find($userId)->update(['rate' => intval('rate') + 1, 'updated_at' => $date]);

or

User::find($userId)->update(['rate' => 'rate' + 1, 'updated_at' => $date]);

Is there a problem with these?

11th August, 2018

alihoushyaripour started a new conversation How To Pass Manual Parameters To Resource Array? • 1 month ago

Hi,

This is my resource class:

class NumberResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'number' => $this->number,
            'date' => [
                'create' => (string)$this->created_at,
                'update' => (string)$this->updated_at
            ]
        ];
    }
}

It work well, but if I want to use a parameter instead of a model's parameter like this:

class NumberResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // parameter
        $number = rand(0, 1);

        return [
            'id' => $this->id,
            'number' => $number,
            'date' => [
                'create' => (string)$this->created_at,
                'update' => (string)$this->updated_at
            ]
        ];
    }
}

show me this error and not work...

"Failed calling Illuminate\Http\Resources\Json\AnonymousResourceCollection::jsonSerialize()"

What happen?!

I need to fill some response parameters with local and manual parameters.

9th August, 2018

alihoushyaripour left a reply on How To Run One Migration File As Separate? • 1 month ago

Can anyone help me please !?

alihoushyaripour left a reply on How To Use Dependency Injection In A Class With Static Functions? • 1 month ago

@martinbean Thank you my friend, I realized well.

8th August, 2018

alihoushyaripour left a reply on How To Use Dependency Injection In A Class With Static Functions? • 1 month ago

@phpMick

I want to use a service's function in my static class.

alihoushyaripour left a reply on How To Use Dependency Injection In A Class With Static Functions? • 1 month ago

@phpMick

'self' used for functions, not parameters.

alihoushyaripour started a new conversation How To Use Dependency Injection In A Class With Static Functions? • 1 month ago

Hi,

I have a class with static functions, that this is:

class login
{
    // parameters
    private $service;

    /**
     * login constructor.
     * @param LoginService $service
     */
    function __construct(LoginService $service)
    {
        $this->service = $service;
    }

    /**
     * @param $request
     * @param bool $mandatory
     * @return bool
     */
     public static function check(Request $request, $mandatory = true)
     {
        // user info
        $id = $request->user->id;
        $token = $request->user->token;

        // check user is login or not
        $this->service->check($id, $token);
     }
}

In this line:

// check user is login or not
$this->service->check($id, $token);

I have an error that say:

$this is not accessible in static content

How can I use it ?!

alihoushyaripour left a reply on Server Response Take Too Long And Not Send Response To Client • 1 month ago

Thank you very much for helping me.

I've tested all that you said, but my problem is still unresolved.

No problem, I'm trying to solve it.

7th August, 2018

alihoushyaripour left a reply on Server Response Take Too Long And Not Send Response To Client • 1 month ago

@Snapey

No, this is my model:

class category extends Model
{
    /**
     * @return bool
     */
    public function is_parent()
    {
        return DB::table('category_relations')->where(['parent_id' => $this->id])->get()->isNotEmpty();
    }

    /**
     * @return bool
     */
    public function is_child()
    {
        return DB::table('category_relations')->where(['sub_id' => $this->id])->get()->isNotEmpty();
    }

    /**
     * @return bool
     */
    public function has_child()
    {
        return DB::table('category_relations')->where(['parent_id' => $this->id])->get()->isNotEmpty();
    }
}

It have 3 function to get 3 parameters for response. (accessible in CategoryResource)

I several times check route in several states and codes, in all of them when program arrive to this line: (in controller)

// get categories
$categories = $this->categoryService->all();

it seems to be stuck in an infinite loop and request fails.

alihoushyaripour left a reply on Server Response Take Too Long And Not Send Response To Client • 1 month ago

@Cronix

I tested and write eloquent instead of service and repository and also not work.

The number of records is less than 20.

alihoushyaripour left a reply on Server Response Take Too Long And Not Send Response To Client • 1 month ago

@Snapey

Hi, I did what you said, and nothing changed.

I think that where I am using dependency, the problem occurs.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.