Talinon

Member Since 5 Years Ago

Toronto

Experience Points
248,520
Total
Experience

1,480 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
1156
Lessons
Completed
Best Reply Awards
208
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

  • Community Pillar

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

Level 50
248,520 XP
Apr
13
1 month ago
Activity icon

Replied to Random "Network Has Changed" Error

Why would an android be hardwired?!

Besides, I described that I confirmed it by testing.

Activity icon

Started a new Conversation Random "Network Has Changed" Error

Hello All,

I've been pulling my hair out over this for a couple days. I'll describe my thought process on this.

Back end is LAMP stack, front end is Vue, Axios

I've developed a mobile-first app where a key feature is to submit a photo. Nothing out of the ordinary, just a straight-forward single photo which can be selected or captured by the device's camera.

I received a report that a user was experiencing random error message when trying to submit a photo. On repeated attempts, it would eventually succeed. After extensive testing, here are my findings:

This does NOT happen on my development server, only production. Both production and development are the exact same set up, running under linux.

My first thought was the server rejected photos of high quality/size due to Apache's file or POST size maximum settings within php.ini - this was not the case.

Second thought was validation.. not the case, there is no 422.. in fact, it appears the request never hits the server.

I then discovered that it seems to ONLY be happening on Android devices using Chrome. iPhones do not experience this "random" error, nor does using Firefox on Android.

So, my next thought was to enable Developer Mode on the Android and see what is going on within the developer tools.

Turns out, the device is getting a very uninformative "Network has changed" error. Again, just to hammer it home, this seems completely random. Usually on the next attempt, it succeeds. Sometimes it succeeds on the first attempt.

Reviewing the POST request under the network tab, it shows it requesting the correct HTTPS URL and endpoint. Under Content-Type it shows "multi-part/form-data; boundary=----WebkitFormBoundary(random chars)"

I understand the Boundary is used for separator decoding for the server.. but on successful POST requests, it doesn't have this boundary data.. no idea where this is coming from.

So, I then turned to considering CORS being the culprit. Maybe this error is coming from a pre-flight request to the server. My experience with CORS is limited, but I would think that the pre-flight request would show up in Apache's access log... there is nothing. Which I would expect as it's not actually hitting the server, hence the "Network has changed" error.

To be sure, I applied a wildcard to the request headers for Access-Control-Allow-Origin, added all the methods to Access-Control-Request-Method, etc. Random error still occurs.

The app is running on a sub-domain, but I'm convinced it's not CORS related.. why would it sometimes work if it was CORS? it should be consistently rejected.

This leaves me with only one other guess... the app is running on an intranet behind a Cisco VPN. I'm thinking the VPN is doing something flakey which causes the "random" network error. This would also explain why this does not happen on my test server.

But even if that was true - why does it ONLY happen on multipart POST requests? All other requests are fine.. GET, DELETE, PATCH.. no problems.. only on this file upload does it occur. If there was a network error, you'd think it would happen randomly on any network request. Furthermore, why does Firefox not experience this problem?

I'm starting to think this might be some kind of bug within the Android version of Chrome that is being tripped by the VPN.. I've completely exhausted my brain on this one.. does anyone have any idea what is going on?

As a (temporary?) solution, I've added some automatic re-attempt code to the image upload using AxiosRetry. It seems whatever is causing the "Network has changed" error doesn't stick around for long. It always seems to work on the 2nd or 3rd attempt. The only negative impact of this work-around is the potential for the request to take an additional few seconds to succeed, something I can live with.

Even though this work-around has yet to fail and seems to solve the problem, I'd still love to get to the root of why this is happening...

<v-card
    :class="{ 'on-hover': hover, 'mx-auto': 'mx-auto', 'mt-3': 'mt-3' }"
    max-width="250"
    width="250"
    color="teal darken-4"
    @click="triggerPhoto"
>
<input type="file" ref="createPhoto" accept="image/*" capture v-show=false @change="uploadPhoto($event.target.files, null)">


uploadPhoto(photo, entry) {

    if (!photo.length) return;

    this.loading = true;

    let formData = new FormData();

    let url = entry ? entry.id : '';

    formData.append('photo', photo[0]);
    
    const client = axios.create({ });
    axiosRetry(client, { retries: 5, retryCondition: (_error) => true, retryDelay: (retryCount) => { return retryCount * 2000;  } });

    client.post('/photo/' + url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }).then(response => { 

        flash('Successfully uploaded photo');
        this.fetchEntries();

    }).catch(error => {

        flash('Something went wrong - please try again shortly');


    }).finally(() => {

        this.createDialog = false;
        this.loading = false;
});

triggerPhoto() {

    this.$refs.createPhoto.click()

},

Also, when the error happens, the error object within the catch block is empty.

Feb
12
3 months ago
Activity icon

Replied to How To Display Queue From Jobs Table ?

@calin.ionut If you're using the database for your queued jobs, just write an artisan command that queries the jobs table and outputs the data.

If you consider using Redis instead of a database, you can install Horizon which has a nice dashboard and features for monitoring your queues, including "pending" which is what you're trying to do.

Feb
02
3 months ago
Activity icon

Awarded Best Reply on Try Catch Not Working Properly

@swimmer Yes, my example is for vanilla PHP error handling. Either prefix Exception with a slash as shown above, or import it:

use \Exception;
Feb
01
3 months ago
Activity icon

Replied to Try Catch Not Working Properly

@swimmer Yes, my example is for vanilla PHP error handling. Either prefix Exception with a slash as shown above, or import it:

use \Exception;
Jan
31
3 months ago
Activity icon

Replied to Music While Coding

I prefer complete silence, but whenever that isn't possible and I need to drown out background noise, my preference is classical... With my go to being Mozart

Activity icon

Replied to Try Catch Not Working Properly

@swimmer have you imported \Exception? Otherwise the catch block will be looking for something being thrown with the name "Exception" within the current namespace.

or just add a preceding slash within the catch definition to use the global namespace:


try {
        
    } catch (\Exception $e) {
        // ...

        
    }
Dec
24
4 months ago
Activity icon

Replied to Microsoft Graph API / Onedrive

@carleogden Your code looks fine, at first glance.

To use the Microsoft Graph API, do I need to log every time I run my laravel system (as the examples if you create it from the microsoft pages).

Yes, you need to provide the token upon every request. The access token expires every hour, so you will either need to obtain a new one, or request a refresh token.

I went about handling this by creating a class that acts as a token store, and is responsible for automatically refreshing the token if it's close to expiration. I store the token information using Redis, but you can use whatever you like. I also wrote an abstract class that builds up the Graph/Guzzle object which I extend all my classes that interact with Graph, so I don't need to keep repeating the connection code for every request.

I get a 403 forbidden so I can take it that the access token doesn't work!

I suspect it has to do with your permissions in Azure. Since you have your client id and secrets, it looks like you have already registered your application within Azure AD. Have you added the Microsoft Graph API permissions, such as Directory.Read.All (to view all AD) and User.Read.All (to read all user profiles)

You'll need to add similar permissions for everything you want to grant your application access to.. mailboxes, contacts, calendar events, etc.. Likewise, if you want your application to be able to write, you will need to grant .ReadWrite.All access for each.

To make it even more complicated, you'll need either a Global, Application or Clould Application Administrator to grant the permission changes. If you have that access, or know of someone who does, then great.. if not, you'll have to hunt down someone who can (your host provider)

Dec
17
5 months ago
Activity icon

Awarded Best Reply on Class 'App\Providers\SwitchLocale' Not Found

@gianmarx

Sorry, that was a typo.. should be new \Day4\SwitchLocale\SwitchLocale([.. I'll update the snippet

Getting yourself a coding editor that automatically resolves the namespace can help in these situations.

Activity icon

Replied to Class 'App\Providers\SwitchLocale' Not Found

@gianmarx

Sorry, that was a typo.. should be new \Day4\SwitchLocale\SwitchLocale([.. I'll update the snippet

Getting yourself a coding editor that automatically resolves the namespace can help in these situations.

Activity icon

Replied to Class 'App\Providers\SwitchLocale' Not Found

@gianmarx The error is very straight forward. It doesn't know what SwitchLocale is. It has nothing to do with the package, Laravel, or the Service Provider.. it is a basic PHP error that is saying it can't find SwitchLocale because you haven't told it where to find it. It doesn't matter if you imported it into your User resource, that is a different class and has nothing to do with your current error.

So I'll explain again.. you need to either import SwitchLocale into the class where tools() is defined, or supply the full namespace. I already pasted the exact line for you, but I'll provide the entire method this time:

public function tools()
{
    return [
        new \Day4\SwitchLocale\SwitchLocale([
            "locales" => [
                "en" => "English",
                "de" => "German"
            ],
            "useFallback" => false,
            "customDetailToolbar" => false //optional
        ])
    ];
}

I suspect the guide either missed that information, or assumed you knew to import it.

Activity icon

Replied to Call A Function From Another Controller

@eliekhazzaka If you want people to help you, you're going to have to do better than "didn't work"

What didn't work about it? was there an error? what was the code you tried?

Activity icon

Replied to Class 'App\Providers\SwitchLocale' Not Found

@gianmarx That's code from your App\Nova\User class.. your error is apparently coming from the Service Provider.

You need to import or use the full namespace in the file wherever tools() is defined... which I suspect is app\Providers\NovaServiceProvider.php

Activity icon

Replied to Class 'App\Providers\SwitchLocale' Not Found

@gianmarx You still need to tell your provider where to find that class.. so you need to either use the full namespace, or import it at the top of the class:

use Day4\SwitchLocale\SwitchLocale;

or:

new \Day4\SwitchLocale\SwitchLocale([
	//...
Dec
14
5 months ago
Activity icon

Replied to Serialization Of 'closure' Is Not Allowed In Job

@crazylife The request object is a complex object with a lot of data - some if that having closures. You don't want to serialize the entire request object because it is massive. Instead, just pass the specific data that the job needs. In many cases, this might just be a single model. If using the SerializesModels trait, its serialization will be further simplified to just it's primary id, which will get queried upon the job's execution.

Dec
09
5 months ago
Activity icon

Replied to Upgrade To Laravel 8 And PHP 8 Gives Laravel Error

@vincej This video should help:

https://laracasts.com/series/whats-new-in-laravel-8/episodes/11

Around the 5 minute mark, Jeffrey demonstrates how you can use a forked version in place of a package.

If you have issues with the fork, a last resort option would be (and I even hate myself while typing this as its a cardinal sin) to change the source code in the vendor directory. I only mention this because it's such a small change, and it is likely temporary until laravelcollective/html updates or merges the PR.

You can see the change here:

https://github.com/LaravelCollective/html/pull/671/commits/06ae76ab165af1cbf16103f0bf442363a90799e6

It's just a one-liner... if you're really careful until they update their repo, you could just slip that into the vendor source. You Just need to remember it'll revert back if you ever run a composer update/install.

Activity icon

Awarded Best Reply on Prevent Queue From Trying In Case Of Fail

Yes, when set to 0 they will re-attempt indefinitely.

Dec
08
5 months ago
Activity icon

Replied to Upgrade To Laravel 8 And PHP 8 Gives Laravel Error

@vincej The version numbers between Collective and the Laravel Framework are not aligned. Collective version 6.2 has support for Laravel 8.

I do not believe your issue is with Laravel 8, but is a compatibility problems with PHP 8 and the Collective package. You can see a Pull Request here with the same error you have:

https://github.com/LaravelCollective/html/pull/671

So, I think your options are:

  1. Get rid of the package and update your views to NOT use Collective (many developers have gone this way)
  2. Downgrade PHP
  3. Install a fork of Collective where they have the fix

For #3 - see https://github.com/repat/html

Activity icon

Replied to Upgrade To Laravel 8 And PHP 8 Gives Laravel Error

@vincej try clearing your view cache: php artisan view:clear

Activity icon

Awarded Best Reply on Where/what Should Be A Single Service/method For Generating Og:images

@iign Calling one controller from another controller is considered bad practice :) Declaring static functions is also generally frowned upon without good reason.

I'd do this instead:

You can store the service class literally anywhere you think makes organizational sense. For this example, I'll just use App\Services


use App\Services\ImageService; 

public function store(ImageService $imageService)
{
	$new_job = JobPost::updateOrCreate(...);

	$imageService->generate($new_job);
}

ImageService.php

namespace App\Services;

class ImageService
{

	public function generate(JobPost $job)
	{

		// call intervention, store to disk, whatever else...

	}


}
Activity icon

Replied to Where/what Should Be A Single Service/method For Generating Og:images

@iign Calling one controller from another controller is considered bad practice :) Declaring static functions is also generally frowned upon without good reason.

I'd do this instead:

You can store the service class literally anywhere you think makes organizational sense. For this example, I'll just use App\Services


use App\Services\ImageService; 

public function store(ImageService $imageService)
{
	$new_job = JobPost::updateOrCreate(...);

	$imageService->generate($new_job);
}

ImageService.php

namespace App\Services;

class ImageService
{

	public function generate(JobPost $job)
	{

		// call intervention, store to disk, whatever else...

	}


}
Activity icon

Replied to Where/what Should Be A Single Service/method For Generating Og:images

@iign You could absolutely create a dedicated service class for such a thing. Extract it to its own class where you can call it from either of your controllers (or Livewire component)

This could be as simple as:

public function store()
{

	// assuming the listing information is within the request
	(new ImageService)->store(request()->all());

}

If you want to get fancy, you can have Laravel autoamtically resolve it for you using Dependency Injection:

public function store(ImageService $service)
{

	$service->store(request()->all();

}

In the above example, Laravel will automatically resolve and instantiate the class for you. Even if your ImageService has dependencies, Laravel will still attempt to resolve those using reflection.

ImageService.php:


public function store($data)
{

	// logic here

}

If you really want to get fancy, you could make a binding into Laravel's Service Container, where you can inject a specific implementation of your service class. That way, if you ever wanted to swap out the service class for another, you just need to change one line of code and it'll be injected everywhere your app resolves it. This is getting into the realm of advanced patterns, so I won't go into that.. but if you're interested, you can read more about it here:

https://laravel.com/docs/8.x/container#binding

Activity icon

Awarded Best Reply on How To Simplify This Validation?

@adgower With that much validation, I'd consider starting off by refactoring all that to a dedicated Form Request class:

https://laravel.com/docs/8.x/validation#form-request-validation

The way you currently have it structured, in some cases, it would not display all the possible error messages if the first validate block doesn't pass.

I don't see any point in doing all your conditional if statements. You can add the extra rules to the main validation array and they will only be enforced if they are conditionally required (according to your required_without_all)

So I'd do something like this:

    public function rules()
    {
        
        return [
	'first_name'     => 'required',
        'last_name'      => 'required',
        'email'          => 'required_without_all:id_number,dob|nullable|email',
        'id_number'     => 'required_without_all:email,dob|nullable|digits:4',
        'dob'            => 'required_without_all:email,id_number|nullable|date_format:Y-m-d',
        'hours_per_week' => 'nullable|numeric',
        'hours_per_day'  => 'nullable|numeric',
        'supervisor'     => 'nullable|string',
        'start_date'     => 'date_format:Y-m-d'        
	];

}



But, if you do need to add conditional rules, you can do so with something like:

 public function rules()
    {
        
        $rules = [
		'first_name'     => 'required',
	        'last_name'      => 'required',
	        'email'          => 'required_without_all:id_number,dob|nullable|email',
	        'id_number'     => 'required_without_all:email,dob|nullable|digits:4',
	        'dob'            => 'required_without_all:email,id_number|nullable|date_format:Y-m-d',
	        'hours_per_week' => 'nullable|numeric',
	        'hours_per_day'  => 'nullable|numeric',
	        'supervisor'     => 'nullable|string',
	        'start_date'     => 'date_format:Y-m-d'        
	];

	if (request->has('someField') && request->missing('someOtherField') {

		$rules += [
			'conditionalRule' => 'required|string'
			// ....
		];

	}

	return $rules;

Activity icon

Replied to How To Simplify This Validation?

@adgower With that much validation, I'd consider starting off by refactoring all that to a dedicated Form Request class:

https://laravel.com/docs/8.x/validation#form-request-validation

The way you currently have it structured, in some cases, it would not display all the possible error messages if the first validate block doesn't pass.

I don't see any point in doing all your conditional if statements. You can add the extra rules to the main validation array and they will only be enforced if they are conditionally required (according to your required_without_all)

So I'd do something like this:

    public function rules()
    {
        
        return [
	'first_name'     => 'required',
        'last_name'      => 'required',
        'email'          => 'required_without_all:id_number,dob|nullable|email',
        'id_number'     => 'required_without_all:email,dob|nullable|digits:4',
        'dob'            => 'required_without_all:email,id_number|nullable|date_format:Y-m-d',
        'hours_per_week' => 'nullable|numeric',
        'hours_per_day'  => 'nullable|numeric',
        'supervisor'     => 'nullable|string',
        'start_date'     => 'date_format:Y-m-d'        
	];

}



But, if you do need to add conditional rules, you can do so with something like:

 public function rules()
    {
        
        $rules = [
		'first_name'     => 'required',
	        'last_name'      => 'required',
	        'email'          => 'required_without_all:id_number,dob|nullable|email',
	        'id_number'     => 'required_without_all:email,dob|nullable|digits:4',
	        'dob'            => 'required_without_all:email,id_number|nullable|date_format:Y-m-d',
	        'hours_per_week' => 'nullable|numeric',
	        'hours_per_day'  => 'nullable|numeric',
	        'supervisor'     => 'nullable|string',
	        'start_date'     => 'date_format:Y-m-d'        
	];

	if (request->has('someField') && request->missing('someOtherField') {

		$rules += [
			'conditionalRule' => 'required|string'
			// ....
		];

	}

	return $rules;

Activity icon

Replied to Prevent Queue From Trying In Case Of Fail

Yes, when set to 0 they will re-attempt indefinitely.

Activity icon

Replied to Prevent Queue From Trying In Case Of Fail

It's "tries" not "retries"... so one attempt.

Dec
02
5 months ago
Activity icon

Awarded Best Reply on __toString() Not Working In Class Extended From DateTIme

@jaynarayan createFromFormat() is a static function that will return a new instance of DateTime, not a new instance of your TheDate.

Nov
30
5 months ago
Activity icon

Replied to __toString() Not Working In Class Extended From DateTIme

@jaynarayan createFromFormat() is a static function that will return a new instance of DateTime, not a new instance of your TheDate.

Activity icon

Awarded Best Reply on Sales/2020 Page 500 Error?

@m4rinos I would suggest to contact support by following the link at the bottom of the page

Nov
29
5 months ago
Activity icon

Replied to Sales/2020 Page 500 Error?

@m4rinos I would suggest to contact support by following the link at the bottom of the page

Nov
27
5 months ago
Activity icon

Awarded Best Reply on Don't Match Regex Expression If String IS Certain String

@bufferoverflow

This might be what you're looking for?

^(?!(domain\.com))[a-z0-9.\-]+
Activity icon

Replied to Don't Match Regex Expression If String IS Certain String

@bufferoverflow

This might be what you're looking for?

^(?!(domain\.com))[a-z0-9.\-]+
Nov
26
5 months ago
Activity icon

Awarded Best Reply on Problem With UploadedFile::fake() And PHPUnit Test - Unable To Find A File At Path

@pazitron You don't need to chain it there.. the test is only making the fake file to include within the POST request. You only need to update your controller with storeAs() to be specific about the name. I've never used just store(), I've always used storeAs() so I can sanitize the filename. You can get the filename within your controller using request()->file('image')->getClientOriginalName() then do whatever you want with the string before passing it into the storeAs() method.

Activity icon

Replied to Problem With UploadedFile::fake() And PHPUnit Test - Unable To Find A File At Path

@pazitron You don't need to chain it there.. the test is only making the fake file to include within the POST request. You only need to update your controller with storeAs() to be specific about the name. I've never used just store(), I've always used storeAs() so I can sanitize the filename. You can get the filename within your controller using request()->file('image')->getClientOriginalName() then do whatever you want with the string before passing it into the storeAs() method.

Activity icon

Replied to Problem With UploadedFile::fake() And PHPUnit Test - Unable To Find A File At Path

@pazitron Confirm to see if the file is being stored. A temporary file should be created in your storage/framework/testing/disks/public/images/blog_posts/photoA.jpg after you run the test.

According to the documentation:

Note that we only specified a directory name, not a file name. By default, the store method will generate a unique ID to serve as the file name.

So it might be that it's storing it as a random file name, which is why its failing against photoA.. you could try using storeAs() to be specific about the file name

Also make sure you have enctype="multipart/form-data" on your form tag within your markup.

Activity icon

Replied to Problem With UploadedFile::fake() And PHPUnit Test - Unable To Find A File At Path

@pazitron You're still not asserting against the same path as you're storing the file within your controller. You're asserting that photoA.jpg exists in the root directory of your public disk, while in your controller you're storing it under /images/blog_posts

Activity icon

Replied to Problem With UploadedFile::fake() And PHPUnit Test - Unable To Find A File At Path

@pazitron Within your controller, you have it saving to /images/blog_posts on your public disk, but in your test, you have it asserting against the root path of your local disk.

Nov
25
5 months ago
Activity icon

Replied to Specifying Date Range For Index Page Of API.

@phpmick There is nothing wrong with using query strings to specify your date range, that is how most cloud APIs handle GET requests. The format you use depends on your requirements. If you're just looking for a simple range, and don't have to consider time or timezones, you can just go with a Y-m-d format. In your backend, you can grab the values via request('to_date') (or whatever you named the query string fields) and/or parse them into Carbon instances.

Nov
24
5 months ago
Activity icon

Awarded Best Reply on Collection Doesn't Make Changes

@crazylife Try changing each to map

each() just iterates over the collection, map() will actually return a modified collection

Activity icon

Replied to Collection Doesn't Make Changes

@crazylife Try changing each to map

each() just iterates over the collection, map() will actually return a modified collection

Activity icon

Awarded Best Reply on SQLSTATE[23000]: Integrity Constraint Violation

@oxbir

You can add user_id to the fillable array, just make sure you do this:

$post = Post::create([
        'user_id' => auth()->id(),
        'title' => $request->title,
        'body' => $request->body,
    ]);

Or:

$post = new Post;
$post->user_id = auth()->id();
$post->title =  $request->title;
$post->body = $request->body;
$post->save();

As for your auth error, make a new thread for a new problem.. don't keep polluting the same thread with different issues.

Nov
23
5 months ago
Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation

@oxbir

You can add user_id to the fillable array, just make sure you do this:

$post = Post::create([
        'user_id' => auth()->id(),
        'title' => $request->title,
        'body' => $request->body,
    ]);

Or:

$post = new Post;
$post->user_id = auth()->id();
$post->title =  $request->title;
$post->body = $request->body;
$post->save();

As for your auth error, make a new thread for a new problem.. don't keep polluting the same thread with different issues.

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation

@oxbir You earlier said you defined $fillable on your model, now you posted it with $guarded??

Change it to fillable, as was suggested 3 hours ago...

And I'd highly suggest against including the user_id field, unless you're going to make sure you handle that within your controller using auth()->id()

protected  $fillable  = [
        'title',
        'body',
    ];
Activity icon

Replied to I Need To Validate A Field Which Cannot Be True If Another Field Is Greater Than 0

@nicolaferrara82 Does using services.* not work?

I just realized I had an error in my first snippet:

'services.*' => [new NonTaxable]

If you can make that work, I would think it would then include an array of errors including the keys?

I remember having to do something like this once, where I came up with a very hacky solution. I think I resorted to just manually inserting the keys into the array returned from the FormRequest's messages() method.

Upon every failed element, I'd add it to an array, then merge it with the FormRequest's message() array.

// in the loop, keep track of every failed element - pseduo code:

$services->reject(function ($service, $key) {

	if ($logicFails) {
		$this->nonTaxableFailures["not_taxable.{$key}"] = "Taxes required with VAT"; 
	}
});



then merge it within the rules():

    public function messages()
    {
    
        return $this->nonTaxableFailures + [
            'someotherrule' => 'some other message',
            'someotherrule2' => 'some other message2'
        ];
    
    }

Then I just had to make sure I handled the errors on the front end.

There might be an easier way.. my situation was very complex. I'm still surprised if just passing in the array doesn't automatically provide you the formatted errors for free?

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation

I'm thinking it's not mass assignment, because I'm pretty sure the query statement wouldn't even have the columns included, which they are according to the query exception.

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation

@oxbir Probably need to add title to your model's mass assignment array.

Post.php

protected $fillable = ['title', 'body'];	

or title and body are not included within the request data. How are you submitting the request?

Activity icon

Replied to I Need To Validate A Field Which Cannot Be True If Another Field Is Greater Than 0

@nicolaferrara82

Create a custom rule, loop over the services array and have it return false if it encounters the condition of vat > 0 and not_taxable !== false

Something like:

 'services.*.not_taxable' => [
	'sometimes:required',
	'boolean',
	new NonTaxable
]
namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class NonTaxable implements Rule
{

    public function passes($attribute, $value) : bool
    {

		return 
			$service['vat'] == 0 ||
 			($service['vat'] > 0 && $service['not_taxable'] === false);

    }

}

I think that would work, I've never tried it for arrays.. it should pass each element of the array into the rule object for validation.

If it doesn't work for some reason, then this might:

 'services' => [new NonTaxable]
    public function passes($attribute, $services) : bool
    {

	return ! $services->reject(function ($service) {
		return 
			$service['vat'] == 0 ||
 			($service['vat'] > 0 && $service['not_taxable'] === true);
	})->count();

    }


Basically passes the entire array into the rule object, if a service doesn't pass the truth test, it will remain within the collection. So if the count is greater than 0, the passes() method will return false and the validation will fail. I wouldn't reach for this unless the first example doesn't work.

I obviously haven't test, so you might need to fiddle around with it, but hopefully gives you an idea on how to tackle the validation.

Activity icon

Replied to Status Code: 500 Internal Server Error

Your original question was for a HTTP 500 error, which I pointed you towards first fixing a problem within your exception handler. That is not your Handler.php

Now you're posting javascript errors. So you have three separate errors that we know of.

Activity icon

Replied to Get Info Sent In Session From One Controller To Another

@msslgomez Why wouldn't you just handle the conditional return within the same controller?

// ......

if ($delivery) {
        $joker->delivery_customer = $delivery['customer'];
        $joker->delivery_phone = $delivery['phone'];
        $joker->delivery_email = $delivery['email'];
    }

//    return redirect('cart/joker_summary')->with('info', $joker);

return Inertia::render('Cart/JokerSummary', [
            'joker' => $joker
        ]);