alihoushyaripour

alihoushyaripour

Member Since 11 Months Ago

Experience Points 5,230
Experience Level 2

4,770 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Reply
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.

29 Apr
1 month ago

alihoushyaripour started a new conversation Crawlers Are Not Wait To Vuejs Render Complete

Hi

I write a multi page website using pure vue-js and html and not vue-cli, but when google crawler want to crawl every page content, show me error for {{ }} brakets and was indexed content before vue-js render complete.

How can I resolve it ?

If should I write my website using vue-cli ? or exist any way ?

16 Apr
2 months ago

alihoushyaripour left a reply on How To Access To Another Vue Instance In DOM Of One Instance?

@FTIERSCH - Thank you my friend, I test it now but don't work, is this because I use vue in raw html code?

alihoushyaripour started a new conversation How To Access To Another Vue Instance In DOM Of One Instance?

Hi,

This is my code:

<body>
<div v-show="show_section" id="app1" v-cloak>
    ...
</div>
<div v-show="show_section" id="app2" v-cloak>
    <button @click="vueIns1.plusCounter()"></button>
    ...
</div>
</body>
<script type="text/javascript">
    // app1 vue instance
    let vueIns1 = new Vue({
        el: '#app1',
        data: {
            show_section: false,
            counter: 0,
            ...
        },
        methods: {
            allApiDataFetched() {
                this.show_section = true;
                document.getElementById('preloader').style.display = 'none';
            },
            plusCounter() {
                this.counter++;
            },
            ...
        },
        ...
    });

    // app2 vue instance
    let vueIns2 = new Vue({
        el: '#app2',
        data: {
            show_section: false,
            ...
        },
        methods: {
            allApiDataFetched() {
                this.show_section = true;
                document.getElementById('preloader').style.display = 'none';
            },
            ...
        },
        ...
    });
</script>

I want to access to one of the vue1Ins methods in DOM of vue2Ins, but can't!

How can I access it? is it possible?

15 Apr
2 months ago

alihoushyaripour left a reply on Why Vue.js Not Work When Exist V-show Condition In Body?

@FTIERSCH - Thanks for your desc, but when I use v-if HTML code not removed, like v-show. When I used v-show mousehover, vuejs event and none of them not work. Also I put preloader code inside my vuejs app, but in console this error logged:

show_section parameter not defined.

I'm so confused, it's a strange thing

alihoushyaripour started a new conversation Why Vue.js Not Work When Exist V-show Condition In Body?

Hi,

I have a html file that call many api in that, I make a pre-loader for page and want to show page everytime all of api data fetched, because that I have a boolean property to check and show body. I did this in two ways...

1-

<body>
<div id="preloader"></div>
<div v-show="show_section" id="app" v-cloak></div?
</body>
<script type="text/javascript">
    let vue = new Vue({
        el: '#app',
        data: {
            show_section: false,
        },
        methods: {
            allApiDataFetched() {
                this.show_section = true;
                document.getElementById('preloader').style.display = 'none';
            }
        }
    });
</script>

2-

<body>
<div id="preloader"></div>
<div v-if="show_section" id="app" v-cloak></div?
</body>
<script type="text/javascript">
    let vue = new Vue({
        el: '#app',
        data: {
            show_section: false,
        },
        methods: {
            allApiDataFetched() {
                this.show_section = true;
                document.getElementById('preloader').style.display = 'none';
            }
        }
    });
</script>

The first used v-show and second used v-if But there is a problem in this case, why when I use v-if the vue logic, methods, computed and other be detected by browser and worked successfully but jquery and css not detected and not worked, and when I used v-show it works exactly the opposite, css and jquery detected and worked but none of the vue method, data, logic and so on not work at all.

But why? I need to use one of them.

06 Apr
2 months ago

alihoushyaripour left a reply on How To Hide Ajax Url From The User's Perspective In Js?

@NASH - Ok my friend, but which data need to save in session? Is use of session enough in this case? or need to use Passport authorization also?

my case is a blade page that redirect to a payment page api (like paypal) and after user's payment complete, back to this blade page and after that by click on a button in this page, user redirect to mobile application.

alihoushyaripour started a new conversation How To Hide Ajax Url From The User's Perspective In Js?

Hi, I'm hope you're fine.

In a blade file I write several ajax or axios that if my website open in chrome, firefox or other browser, from this directory everyone can see my api routes:

Elements tab > script tag in html code > ajax instance

but this is not good and every time that I was opened a powerful website that make with laravel, I haven't seen any url in their html code in Elements tab.

But why? what should I do to hide my apis?

19 Mar
2 months ago
18 Mar
2 months ago

alihoushyaripour left a reply on How To Render Html Code After Vuejs?

@CRONIX - Thanks @cronix but not work for me, nothing changed, what's the reason?

alihoushyaripour started a new conversation How To Render Html Files After Vuejs?

Hi,

I have a fairly heavy website that loads a lot of api on its first page. The overall body skeleton of my website is as follows:

...
<div id="app">
    <div v-if="!data_fetched" id="loader"></div>
    <div v-else id="content"></div>
</div>
...

Now my problem is that browser first render html code (before vuejs instantiate created) and show div tag with content id, and a few seconds after that vuejs instantiate was create, show div tag with loader tag and show my gif loader and again after a few seconds that data fetched completely, div tag with content id was show again.

But I want to don't show content tag until data fetched completely, what should I do?

06 Mar
3 months ago

alihoushyaripour started a new conversation How To Close Connection In Response Model?

Hi, I have an android application that need to received response with Connection: close and not Connection: keep-alive

I tried very methods before send response like these:

set_time_limit(0);
ignore_user_abort(true);
ini_set('default_socket_timeout', 0);
$_SERVER['HTTP_CONNECTION'] = 'close';
unset(apache_request_headers()['Connection']);

return response()->json(['headers' => ['Connection' => 'close']], 200, ['Connection' => 'close'])->withHeaders(['Connection' => 'close']);

but not work and again in response header, Connection parameter have keep-alive value.

Also I was changed Apache config and set Connection KeepAlive parameters to Off, but don't work again.

How can I close it? anyone can help me?

05 Mar
3 months ago

alihoushyaripour left a reply on How To Write This Mysql Query Using Eloquent?

@GORAKH - Yes my friend, I test now and both of them worked for me, thank you.

I set second answer as Best Answer because it's write using eloquent and be beauty and clean.

alihoushyaripour left a reply on How To Write This Mysql Query Using Eloquent?

@GORAKH - I was write this first, but all of 4 whereDate run as && together:

\App\Models\Game::whereNull('deleted_at')
    ->whereDate('started_at', '>=', $now)->whereDate('started_at', '<=', $afterTomorrow)
    ->whereDate('started_at', '<=', $now)->whereDate('finished_at', '>=', $now)
    ->orderBy('created_at', 'desc');

and then I was changed query to this:

\App\Models\Game::whereNull('deleted_at')
    ->whereDate('started_at', '>=', $now)->whereDate('started_at', '<=', $afterTomorrow)
    ->orWhereDate('started_at', '<=', $now)->whereDate('finished_at', '>=', $now)
    ->orderBy('created_at', 'desc');

but the first to the third query is executed correctly, but the fourth qurry doesn't executed correctly, because the first and second whereDate must be and together, and also the third and fourth whereDate query must be and together, and then the result of these two queries must be or together.

alihoushyaripour left a reply on How To Write This Mysql Query Using Eloquent?

@GORAKH - OK, but my query is like this:

( whereDate && whereDate ) || (whereDate && whereDate )

How and Where can I used orWhere in this structure? like this?

( whereDate && whereDate ) || (orWhereDate && whereDate )

alihoushyaripour started a new conversation How To Write This Mysql Query Using Eloquent?

Hi, I have a model with name Game and I want to write a eloquent query with multiple Date where, I was write this query as raw but can't write it using eloquent to fetch data as model.

game model class:

{
    // other parameters
    ....
    timestamp created_at;
    timestamp updated_at;
    timestamp started_at;
    timestamp finished_at;
    timestamp deleted_at;
}

php code and mysql query:

$now = \Carbon\Carbon::now()->format('Y-m-d H:i:s');
$afterTomorrow = \Carbon\Carbon::today()->addDays(2)->format('Y-m-d H:i:s');
\DB::raw("select * from games where ( started_at >= $now and started_at <= $afterTomorrow ) or ( started_at <= $now && finished_at >= $now )")->getValue();

Anyone can help me?

04 Mar
3 months ago

alihoushyaripour left a reply on Controller Function With Request Class Input Not Found From Route

@SERGIU17 - This is my request class:

class User 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 [
           'user' => ['required', 'array'],
           'user.first_name' => ['required', 'string'],
           'user.last_name' => ['required', 'string'],
           'user.email' => ['required', 'string'],
           'user.mobile_number' => ['required', 'string'],
           'user.device_id' => ['required', 'string'],
           'user.device_os' => ['required', 'string', Rule::in(['android', 'ios'])]
        ];
    }
}

I noticed a subject, in laravel 5.7, if the rules of a parameter were violated, the corresponding error would be returned in response, but now if for example I would enter the device_os other than android and ios, then the error would be 404 not found.

alihoushyaripour started a new conversation Controller Function With Request Class Input Not Found From Route

Hi, I have a function in controller with name updateUser(), I pass relevant request class as an input to it and when I call it from postman, give me 404 Not Found error, and when I don't pass request class as an input to it, route worked successfully.

but why? I have not seen such a thing in laravel 5.7 before. is this a change in laravel 5.8? because my project was built with laravel 5.8

/**
 * don't work, 404 not found error
 */
public function updateUser(\App\Http\Requests\User $request)
{
    $request = $request->validated();

    ...
}

/**
 * work successfully
 */
public function updateUser()
{
    $request = request()->all();

    ...
}
23 Feb
3 months ago

alihoushyaripour started a new conversation How To Use The Separator Between Letters Of A String?

Hi, I want to use , as separator to put it between price integer like this, convert first to second:

285500000 => 285,500,000
25000 => 25,000
1600 => 1,600
850 => 850 (not changed)

I can do it with a complicated function, but is there any better way?

11 Dec
6 months ago

alihoushyaripour left a reply on How To Make Image File From An External Url?

@WILK_RANDALL - That's good my friend, but my project is modular and my uploadImage module get image from $_FILES array and put it to storage path.

Is there any way?

alihoushyaripour started a new conversation How To Make Image File From An External Url?

Hi,

I want to make Image file from an external URL and put it to $_FILES php global array.

How can I do it?

10 Dec
6 months ago

alihoushyaripour left a reply on How To Push A Job Into Queue?

@TALINON - Yes, this is my job code:

class SendSimpleMessageToUserByPusheId implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(string $pusheId, string $title, string $content)
    {
        //
    }

    public function handle()
    {
        //
    }
}

Is the problem elsewhere?

09 Dec
6 months ago

alihoushyaripour started a new conversation How To Push A Job To Queue?

Hi,

I have a job and want to push it in queue to start with 500 ms delays, I was write this code:

\Queue::push(new SendSimpleNotification('token', 'title', 'content'));

But when code is running and come to this line, if this job take 5 seconds to finished, code wait 5 seconds in this line and it doesn't pass quickly from this line to run it queue later.

Notice that I use a simple curl in my job class (handle function).

06 Dec
6 months ago

alihoushyaripour started a new conversation What Exactly Does --optimize-autoloader Command?

Hi,

I want to publish my laravel project, because that I read this document:

https://laravel.com/docs/5.6/deployment

It says run this artisan command for optimization:

composer install --optimize-autoloader --no-dev

I was run it but this command was removed 32 packages of my project. It showed me this:

Loading composer repositories with package information
Installing dependencies from lock file
Package operations: 0 installs, 0 updates, 32 removals
  - Removing webmozart/assert (1.3.0)
  - Removing theseer/tokenizer (1.1.0)
  - Removing symfony/thanks (v1.1.0)
  - Removing sebastian/version (2.0.1)
  - Removing sebastian/resource-operations (2.0.1)
  - Removing sebastian/recursion-context (3.0.0)
  - Removing sebastian/object-reflector (1.1.1)
  - Removing sebastian/object-enumerator (3.0.3)
  - Removing sebastian/global-state (2.0.0)
  - Removing sebastian/exporter (3.1.0)
  - Removing sebastian/environment (4.0.1)
  - Removing sebastian/diff (3.0.1)
  - Removing sebastian/comparator (3.0.2)
  - Removing sebastian/code-unit-reverse-lookup (1.0.1)
  - Removing phpunit/phpunit (7.4.5)
  - Removing phpunit/php-token-stream (3.0.1)
  - Removing phpunit/php-timer (2.0.0)
  - Removing phpunit/php-text-template (1.2.1)
  - Removing phpunit/php-file-iterator (2.0.2)
  - Removing phpunit/php-code-coverage (6.1.4)
  - Removing phpspec/prophecy (1.8.0)
  - Removing phpdocumentor/type-resolver (0.4.0)
  - Removing phpdocumentor/reflection-docblock (4.3.0)
  - Removing phpdocumentor/reflection-common (1.0.1)
  - Removing phar-io/version (2.0.1)
  - Removing phar-io/manifest (1.0.3)
  - Removing myclabs/deep-copy (1.8.1)
  - Removing mockery/mockery (1.2.0)
  - Removing hamcrest/hamcrest-php (v2.0.0)
  - Removing fzaninotto/faker (v1.8.0)
  - Removing filp/whoops (2.3.1)
  - Removing doctrine/instantiator (1.1.0)
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

And now in several place of my code error has occurred.

Class 'SebastianBergmann\ObjectEnumerator\Enumerator' not found.
...

But why? What should I do? Please help me

04 Dec
6 months ago

alihoushyaripour left a reply on What Is The Best Documentation Tool?

@TYKUS - Which one are the best of swagger and slate?

alihoushyaripour started a new conversation What Is The Best Documentation Tool?

Hi,

I want to write document for my routes (that is rest api), I was searched and see many tools but I don't know which is the best for laravel? Are those different from each other for laravel?

Please help me, Thank's

03 Dec
6 months ago

alihoushyaripour started a new conversation How To Get User Ipv4 From Lat/lng?

Hi,

I want to get user state/city of user from his ipv4 address using google static api, but take too long...this is my code:

$lat = $v['lat'];
$lng = $v['lng'];

$json = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=true";

$response = json_decode(file_get_contents($json));

Is there any other faster solution?

24 Nov
6 months ago

alihoushyaripour left a reply on Command "make:model" Is Not Defined.

@SNAPEY - @snapey

OK, don't problem, but I was guessed when command make:model run, several processes will be occurred in background, because command running take about 15 seconds to finished. if I create it manual, will not there be a problem?

alihoushyaripour left a reply on Command "make:model" Is Not Defined.

Who does not have the same problem? Anyone can help me?

alihoushyaripour started a new conversation Command "make:model" Is Not Defined.

Hi,

In the last few days a problem has come to me, and that is when I want to make a model, I write this:

php artisan make:model organizer --migration

and composer show me this message:

Command "make:model" is not defined.

  Did you mean one of these?
      ide-helper:models
      make:auth
      make:channel
      make:command
      make:controller
      make:event
      make:exception
      make:factory
      make:job
      make:listener
      make:mail
      make:middleware
      make:migration
      make:notification
      make:observer
      make:policy
      make:provider
      make:request
      make:resource
      make:rule
      make:seeder
      make:test

but why?

I test all of this command to solve it but I didn't succeed.

php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan clear-compiled
composer clear-cache
composer update
composer dump-autoload

What should I do?!

19 Nov
6 months ago

alihoushyaripour started a new conversation How To Handle Chaining Request From Client?

Hi,

I have a route that in that I have several select, several insert and several update using eloquent, because that I used transaction like this for my module to prevent mistake and inconsistency between models:

\DB::transaction(function () use () {
    // select

    // select

    // select

    // insert

    // update

    // update

    // insert
});

And for example when received 20 requests call from client, 15 of them do successfully and 5 of them return this exception:

sqlstate 40001 serialization failure deadlock error

I want to use queue and job for this module, but because I have several insert and update query in module, I can't use it.

Is there any solution for this? for example I make a separate jobs for every insert or update and dispatch them chaining.

14 Nov
7 months 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
7 months 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
7 months 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
7 months 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
7 months 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
7 months 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
7 months 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
7 months 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
8 months 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.