alihoushyaripour

alihoushyaripour

Member Since 4 Months Ago

Experience Points 4,230
Experience
Level
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

14 Nov
12 hours ago

alihoushyaripour started a new conversation How To Write Test Case For All Routes?

Hi,

I have a project that wrote all route as RESTful api, with more than 100 routes, and now I want to write test modules for all of them and test everyone of them with differents test case.

I user laravel 5.6

How can I do it? is there any simple way?

13 Nov
1 day ago

alihoushyaripour started a new conversation How To Call \App\Exceptions\Handler Class From Controller?

Hi,

I write try-catch for my controller's function that is like this:

try {
    //code
} catch (\Exception $exception) {
    //here
}

And I want to call render function of \App\Exceptions\Handler class in catch where I write //here, but I don't know how can I write it?

Anyone can help me?

12 Nov
2 days ago

alihoushyaripour started a new conversation How To Change Models Directory Without Any Problem?

Hi,

Since I started writing a project with Laravel, I always used this command to build my models:

php artisan make:model model_name -m

And all of them created in \App\ directory, and now my model numbers are very large, about 50 and now I want to move them into \App\Models\ directory, but there is a problem... I have used them in many places like controllers, services, repositories, static modules and so on.

Because that I need to change many places and there is many risk in it.

Is there any simple way to to change directory of them without any risks and manual changes?

alihoushyaripour left a reply on How To Change Login Parameters In Passport?

I'm sorry, I was hurried a bit, finally I found the answer.

Add this function to user model class:

/**
     * @param $username
     * @return User|\Illuminate\Database\Eloquent\Model|null|object
     */
    public function findForPassport($username)
    {
        return $this->where('phone', $username)->first();
    }

and put name of your field instead of phone in where clause.

alihoushyaripour started a new conversation How To Change Login Parameters In Passport?

Hi,

How can I change login parameters when I use passport, from email to another parameters like phone_number?

Where should I change?

05 Nov
1 week ago

alihoushyaripour started a new conversation How To Make An Multiple Unique Index With A Special Value?

Hi,

I have two column for user with name username and is_active that every active user have an unique username and can exist more than 1 don't active user with similar username, it means that if user want to activate, must him username be unique, else not.

Because that I need to set an unique index according to mentioned conditions.

I was write it like this but not match with condition2:

...
$table->unique(['username', 'is_active']);
...

How can I do it?

04 Nov
1 week ago

alihoushyaripour left a reply on How Do I Check If An Insertion Row Has Been In The Table At A Recent Hour?

I found solution:

$now = \Carbon\Carbon::now()->subHour(1)->toDateTimeString();
$bool = User::where(['id' => $id])->whereDate('created_at', '>', $now)->get()->isEmpty();

You can also use this static functions for date:

subMinute
subHour
subDay
subMonth
subWeek
...

addMinute
addHour
addDay
addMonth
addWeek
...

alihoushyaripour started a new conversation How Do I Check If An Insertion Row Has Been In The Table At A Recent Hour?

Hi,

my question is in title of discussion, how do I check if an insertion row has been in the table at a recent hour using eloquent?

I want to check created_at property of all rows and get inserted rows in recent hour.

23 Oct
3 weeks ago

alihoushyaripour left a reply on How To Filter Collection Array With "not In" Condition?

@crnkovic

Thanks my friend, I have another question, I have two collection with similar schema, I want to get similar values from those, how can I do it?

ex:

// second collection
$col1 = [
    [
        'id': 1,
        'name': 'ali'
    ],
    [
        'id': 2,
        'name': 'amir'
    ],
    [
        'id': 3,
        'name': 'ehsan'
    ],
    [
        'id': 8,
        'name': 'hossein'
    ],
    [
        'id': 15,
        'name': 'reza'
    ]
];

// second collection
$col2 = [
    [
        'id': 3,
        'name': 'ehsan'
    ],
    [
        'id': 8,
        'name': 'hossein'
    ],
    [
        'id': 22,
        'name': 'sina'
    ]
];

// code here

// result
$result = [
    [
        'id': 3,
        'name': 'ehsan'
    ],
    [
        'id': 8,
        'name': 'hossein'
    ]
];

alihoushyaripour started a new conversation How To Filter Collection Array With "not In" Condition?

Hi,

I have a collection like this:

[
    "id",
    "key",
    "value"
];

And want to filter it like this query:

select * from sample_collection where id not in (1, 2, 3, 4, 5)

How can I write this action with filter function or any other function of collections?

20 Oct
3 weeks ago

alihoushyaripour started a new conversation Failed To Parse Time String (۱۳۹۷-00-00 0:0:0) At Position 0 (�): Unexpected Character

I upgrade my laravel from version 5.5 to 5.6 and inesperadamente all of my route give this error:

"DateTime::__construct(): Failed to parse time string (۱۳۹۷-00-00 0:0:0) at position 0 (�): Unexpected character"

but why?

what changed from laravel 5.5 to 5.6?

19 Oct
3 weeks ago

alihoushyaripour left a reply on How To Pass Array Of Parameters With Ajax To Laravel Route?

@Cronix Thank you my friend, your solution helped me. I found problem, in one of headers of ajax, change this:

'Content-Type': 'text/html; charset=utf-8',

to:

'contentType': 'charset=UTF-8'

and work successfully.

alihoushyaripour left a reply on How To Pass Array Of Parameters With Ajax To Laravel Route?

@Cronix Not work again, but thanks for your solution.

alihoushyaripour left a reply on How To Pass Array Of Parameters With Ajax To Laravel Route?

@Cronix I change it, but nothing has been changed and print [ ] again. See this is my html code, where call submitComment:

<div class="card-body">
    <form>
        <div>
            <button type="submit" class="btn btn-primary" onclick="submitComment();">submit comment</button>
        </div>
    </form>
</div>

alihoushyaripour started a new conversation How To Pass Array Of Parameters With Ajax To Laravel Route?

Hi,

I want to pass some parameters as array with an ajax request to a request, I write this:

$.ajax(url, {
                method:'PUT',
                data: {
            p1: 'sample text',
            p2: true,
            p3: 25
        },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
                    'Content-Type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Credentials': false,
                    'Access-Control-Allow-Origin': 'http://localhost:8000'
                },
                success: function(data) {
                    if (data.status === 'failed') {
                        console.log(data.message);
                        alert(JSON.stringify(data.message));
                    } else if (data.status === 'success') {
                        location.href = 'http://localhost:8000/';
                        // location.reload(true);
                    } else {
                        // nothing
                    }
                },
                error: function(error) {
                    alert(JSON.stringify(error));
                }
            });

And I print received array in controller like this:

return response()->json(['status' => 'failed', 'message' => $request->all()], 200);

But print [] value and no parameters send to the request!

What should I do?

should change the ajax syntax?

14 Oct
1 month ago

alihoushyaripour left a reply on How To Remove Similar Objects Using Checking A Field Of Those?

@Cronix No I don't use them, See, I get them with 2 different eloquent and save them into two different variable, now how pass them to collection together that's what you say?

alihoushyaripour left a reply on How To Remove Similar Objects Using Checking A Field Of Those?

@Cronix I get from model with eloquent, but need to merge.

alihoushyaripour left a reply on How To Remove Similar Objects Using Checking A Field Of Those?

@Tray2 Not work my friend, your solution is good for one dimensional arrays not an object with multiple field.

Is there exist any other solution?

alihoushyaripour started a new conversation How To Remove Similar Objects Using Checking A Field Of Those?

Hi,

I have 2 object array with name var1 and var2.

Assumption:

always count($var1) <= count($var2)

objects schema:

{
    "code", // integer
    "status_code" // boolean
}

$var1:

[
    {
        "code": 1,
        "status_code": true
    },
    {
        "code": 2,
        "status_code": true
    },
    {
        "code": 3,
        "status_code": true
    },
    {
        "code": 4,
        "status_code": true
    },
    {
        "code": 5,
        "status_code": true
    },
    {
        "code": 6,
        "status_code": true
    },
    {
        "code": 7,
        "status_code": true
    },
    {
        "code": 8,
        "status_code": true
    },
    {
        "code": 9,
        "status_code": true
    },
    {
        "code": 10,
        "status_code": true
    },
    {
        "code": 11,
        "status_code": true
    },
    {
        "code": 12,
        "status_code": true
    },
    {
        "code": 13,
        "status_code": true
    },
    {
        "code": 14,
        "status_code": true
    },
    {
        "code": 15,
        "status_code": true
    }
]

$var2:

[
    {
        "code": 1,
        "status_code": true
    },
    {
        "code": 2,
        "status_code": false
    },
    {
        "code": 4,
        "status_code": true
    },
    {
        "code": 8,
        "status_code": true
    },
    {
        "code": 10,
        "status_code": false
    },
    {
        "code": 15,
        "status_code": false
    }
]

Now I want to combine these 2 objective array, in condition that there is no repetition based on code field and if status_code value in the $var2 array is replaced to $var1

alihoushyaripour left a reply on Problem With Redirect From Controller

@Snapey ok, but what should I do? Is there exist any other way?

alihoushyaripour started a new conversation Problem With Redirect From Controller

Hi,

In a route I need to move between two controllers, I used this code:

// user controller
class UserController extends Controller
{
    public function block() {
        // code

        // redirect
        return redirect()->action('[email protected]', ['user_id' => $user_id, 'blocked_user_id' => $blocked_user_id], 200);
    }
}

// user relationships controller
class UserRelationshipsController extends Controller
{
    public function afterBlock($user_id, $blocked_user_id) {
        // code
    }
}

After a user is blocked, also need to unfollow him and I do that in afterBlock function.

But when I run code, show me this message at last line of block function:

InvalidArgumentException
Action App\Http\Controllers\[email protected] not defined.

But why?

06 Oct
1 month ago

alihoushyaripour started a new conversation How To Log All Route Calling Into File?

Hi,

I want to log all of the route calling with request params into a file to save which route called how many time, now how can I do it?

Is monolog good for that?

And if it's good, where I must use it in my project?

In route.php file, in __construct of every controller or other place?

alihoushyaripour left a reply on How To Upload File Or Image In Public/ Directory?

I found the solution from this link, it's very useful.

https://quickadminpanel.com/blog/file-upload-in-laravel-the-ultimate-guide/

alihoushyaripour started a new conversation How To Upload File Or Image In Public/ Directory?

Hi,

I write this code when my laravel version is 5.6 and its work fine and upload files into public/ directory, but since I upgrade my laravel to 5.7 this code work fine but it uploaded files into storage/app/ directory, and not in public/

I search a lot but not found any same problem with my problem.

What should I do?

04 Oct
1 month ago

alihoushyaripour left a reply on How To Map Model Array Data To Model Class?

When I use methods to make model object, in that line, show me this error:

"preg_match() expects parameter 2 to be string, array given"

alihoushyaripour started a new conversation How To Map Model Array Data To Model Class?

Hi,

I use lucene in my project and I create a same model in lucene for every laravel model, now I query in lucene and get data and I want to pass array data to resource collection to make response data, but resource collection class can't work with array data.

I test these two method and not work for me:

// users array data from lucene
$users = $client->search($request);
// method 1
$usersObj = collect($users)->mapInto(User::class);
// method 2
$usersObj = User::make($users);

Is there any other way?

01 Oct
1 month ago

alihoushyaripour started a new conversation How To Read Repetitive Parameters As Array From Url?

Hi,

From client call a route like this that send to server a list of integers with name id:

id list = [1, 2, 4, 8, 13]
http://localhost:8000/api/v1/users?id=1&id=2&id=4&id=8&id=13

but in laravel when I want to read Request, give me last value that here is 13 and other values not received.

In otherwise in retrofit this is a standard method to put list value in url.

Anyone know how can I read all of list value from route?

29 Sep
1 month ago

alihoushyaripour left a reply on How To Pass Additional Parameters To Resource Class?

@bestmomo because not work this, laravel can't let add additional parameters to resources arrays.

alihoushyaripour started a new conversation How To Pass Additional Parameters To Resource Class?

Hi,

I want to pass additional parameters to this resource class because I need to find this resource class called from where controller, see these:

// resource class
class GiftResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => (integer)$this->id,
            'title' => substr($this->title, 0, 150),
            'description' => (string)$this->description,
            'image' => (string)$this->image,
            'from' => (string)$this->additional->from, //here
        ];
    }
}

user controller:

class UserController extends Controller
{
    public function getById($id)
    {
        // get user

        // get user gift
        $gift = $giftService->getByUserId($id);
        $gift = GiftResource::collection($gift)->additional(['from' => 'UserController']); //here

        ...
    }
}

place controller:

class PlaceController extends Controller
{
    public function getById($id)
    {
        // get place

        // get place gift
        $gift = $giftService->getByPlaceId($id);
        $gift = GiftResource::collection($gift)->additional(['from' => 'PlaceController']); //here

        ...
    }
}

I've heard that exist a parameter with name additional that it's duty is save additional parameters in itself, but this not work and always additional is null.

anyone can help me?

27 Sep
1 month ago

alihoushyaripour started a new conversation Object Parsing Is Faster Or Array Parsing?

Hi,

Which of these code is run faster and use less ram?

// request array
$request = \request()->all();

// parameters
$user = $request['user'];
$address = $place['address'];
$lat = $address]['lat'];
$lng = $address['lng'];
$province = $this->provinceService->getByName($address['province']);
$city = $this->cityService->getByName($address['city']);
// request array
$request = (object)\request()->all();

// parameters
$user = $request->user;
$address = $place->address;
$lat = $address->lat;
$lng = $address->lng;
$province = $this->provinceService->getByName($address->province);
$city = $this->cityService->getByName($address->city);
26 Sep
1 month ago

alihoushyaripour started a new conversation How To Remove Whitespace From Json String?

Hi,

I have a table with a column that has json type and when I want to insert data on it, json string has many whitespace, this is my code:

// json
$json = json_encode(UserResource::collection($users));

// insert
User::create([
    // parameters
]);

How to remove all whitespace from json?

alihoushyaripour left a reply on Difference Between Json And Jsonb In Migration?

@aurawindsurfing Thanks my friend, description was enough.

alihoushyaripour started a new conversation Difference Between Json And Jsonb In Migration?

Hi,

what's difference between json and jsonb in table?

25 Sep
1 month ago

alihoushyaripour started a new conversation How To Prevent Falling This Code In Unlimited Loop In This Case?

Hi, In my project I have App\Services\ and App\Repositories\ directory that every controller connect to service that service is 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 2 model with names User and Contact that every user has many contacts and every contact belongs to one user.

This is user classes:

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

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


// service class
class UserService
{
    private $repository;
    private $contactService;

    public function __construct(UserRepository $repository, ContactService $contactService)
    {
        $this->repository = $repository;
        $this->contactService = $contactService;
    }

    // functions
}


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

    // functions
}

And this is contact classes:

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

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


// service class
class ContactService
{
    private $repository;
    private $userService;

    public function __construct(ContactRepository $repository, UserService $userService)
    {
        $this->repository = $repository;
    }

    // functions
}


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

    // functions
}

When I use UserService, it inject ContactService and ContactService inject UserService and code falling in a unlimited loop. I can't remove injecting of UserService in ContactServicebecause I need some of function that in UserService. I'm confused. Is there any way to bind my service classes in AppServiceProvider or AppServiceContainer?

Or any other way?!

24 Sep
1 month ago

alihoushyaripour left a reply on How To Access Files That Uploaded In Storage Directory With Url?

@Snapey How to make it? with below artisan command symlink created for storage dir only and not storage\images dir.

php artisan storage:link
23 Sep
1 month ago

alihoushyaripour started a new conversation How To Access Files That Uploaded In Storage Directory With Url?

Hi,

I write a code to upload photo, this is that:

// parameters
$fileName = $_FILES[0]['name'];
$path = '/image/';

// upload
request()->file("$name")->storeAs($path, $fileName);

Photo uploaded successfully but I don't have access to storage directory of my project with url, I test these urls and none of them is true:

http://127.0.0.1:8000/public/storage/image/image.jpg
http://127.0.0.1:8000/storage/image/image.jpg
http://127.0.0.1:8000/public/image/image.jpg
http://127.0.0.1:8000/image.jpg
http://127.0.0.1:8000/public/image.jpg
http://127.0.0.1:8000/storage/app/image/image.jpg
http://127.0.0.1:8000/storage/app/image/image.jpg
http://127.0.0.1:8000/app/image/image.jpg
http://127.0.0.1:8000/public/app/image/image.jpg

Also I set permission 777 for storage and storage/image directories and image files, but not work.

What should I do?

22 Sep
1 month ago

alihoushyaripour started a new conversation How To Calculate And Update Users Rank In Score Page?

Hi,

I have user model that have two column with names coin and rank that rank store rank of every user that it's range is from 1 to count of users.

If a user post a photo or follow a user or like a photo or ... he get a coin and base on that user's rank changed according to count of his coin.

Now I have 1M user and every user do 5 activity every day, in every day I must update all of users row 5 * 1M * 1M to have correct rank of every user. Also may 2 users do activity together at a time and this need a terrible update on users table.

What should I do for that?

17 Sep
1 month ago

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

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()
16 Sep
1 month ago

alihoushyaripour left a reply on How To Speed Up Insert Query?

@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?

@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?

@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 ?

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?

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
11 Sep
2 months ago

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

@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?

@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?

@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?

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 ?!