Our Black Friday sale is now live! All individual subscriptions are 50% OFF. This week only!

Talinon

Talinon

Member Since 4 Years Ago

Toronto

Experience Points
239,480
Total
Experience

520 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
1121
Lessons
Completed
Best Reply Awards
199
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.

Level 48
239,480 XP
Nov
24
1 day 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
2 days 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
        ]);

Activity icon

Awarded Best Reply on DB::select() Error Sql #1140

@laurent1979 To my understanding, disabling strict mode as you mentioned, should make it behave like earlier versions where it was possible to make such a query with nonaggregates. Make sure you clear your config cache.

Either way, grouping should be the way you want to go about it anyway. Most engines now behave like this, so avoiding it would be considered bad practice.

Activity icon

Replied to Status Code: 500 Internal Server Error

@shaungbhone A bug in your exception handling is preventing you from easily determining what the problem is with your routes. You might as well fix this now, because it'll keep coming back the next time you have an error. This is the reason why you're getting a 500 error - the server doesn't know what to do so it just blows up.

Post your app/Exceptions/Handler.php file and let's fix that problem first..

Activity icon

Replied to DB::select() Error Sql #1140

@laurent1979 To my understanding, disabling strict mode as you mentioned, should make it behave like earlier versions where it was possible to make such a query with nonaggregates. Make sure you clear your config cache.

Either way, grouping should be the way you want to go about it anyway. Most engines now behave like this, so avoiding it would be considered bad practice.

Activity icon

Replied to DB::select() Error Sql #1140

@laurent1979 Well, your query doesn't make much sense. How is it supposed to count something that isn't aggregated? You just need to do what the error suggests:

$query = 'SELECT count(date) AS total, substr(date, 1, 4) AS annee FROM sort_orders_by_times WHERE date LIKE \'' . $date .'%\' group by annee';

return DB::select($query);
Activity icon

Replied to Status Code: 500 Internal Server Error

@shaungbhone Yes, but the error will bubble up to Laravel's Exception handler, which has an error itself. Your error could be anything. It might be that it can't find your namespaced controller. It might be that you haven't imported (use) the Reply class within your controller. If might be that it can't find your Reply Policy class. It can be anything.

Instead of guess work, you need to fix that error so you can get more informative errors.

Nov
22
3 days ago
Activity icon

Replied to Status Code: 500 Internal Server Error

@shaungbhone

You seem to have a problem with your exception handling, which you should fix first.

Look in your app/Exceptions/Handler.php file on line 68 to see what the problem is. Most likely the undefined $e should be $exception, which is a common error with exception handling convention.

Once you get that fixed, you should get a more meaningful error.

Activity icon

Awarded Best Reply on Why I'm Getting More Threads ?

@faraz73

Try this:


public function definition()
    {
        return [
            'thread_id' => function() {
			Thread::factory()->create();
	    },
            'user_id' => User::factory()->create(),
            'body' => $this->faker->paragraph,
        ];
    }

The code within the closure will only run if you do not specify the thread_id, which should solve your issue

Activity icon

Replied to Status Code: 500 Internal Server Error

@shaungbhone look in your storage/logs directory for the explanation for the 500 error.

Activity icon

Replied to Why I'm Getting More Threads ?

@faraz73

Try this:


public function definition()
    {
        return [
            'thread_id' => function() {
			Thread::factory()->create();
	    },
            'user_id' => User::factory()->create(),
            'body' => $this->faker->paragraph,
        ];
    }

The code within the closure will only run if you do not specify the thread_id, which should solve your issue

Activity icon

Replied to Status Code: 500 Internal Server Error

@shaungbhone The first thing you do when you get a 500 error is check your logs for the reason.

Activity icon

Replied to Laravel 8 From Scratch?

@pt-83 Every couple of years the series gets renewed. Since the current series was started only about a year ago, I wouldn't expect a full re-do for some time yet; probably at least a year. It has 68 thorough episodes, with the latest one being concluded in April of this year. You just need to continue on to the "What's new in Laravel 8" series here:

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

Dedicated series are also available to the major new features, such as Jetstream.

Activity icon

Replied to Where To Find A Deleted View ?

@nikhillvl do you use version control? Such as Git or Svn? If not, this is your lesson to start.

Or depending on your OS, have you tried the recycle/trash bin? :)

Activity icon

Replied to Mass Assignement Laravel

It isn't necessary to have a primary key, but it's considered good practice to have it. Even if you never use it, it doesn't harm anything by having it. If anything, most engines will benefit from having the primary key for performance considerations and indexing.

Anyway, getting back to your original post in this thread, I think it's because you set your field as primary even though it isn't. If you drop the primary() from your migration, and then set your model properties to the following, it'll likely solve that error.. but I still don't recommend this approach.

protected $primaryKey = null;

public $incrementing = false;

You'd be better off just adding a primary, incrementing id field.

Activity icon

Replied to Mass Assignement Laravel

@jokerdz It depends.. but 99% of the time, every table has its own primary key, otherwise how are you going to perform an action on a specific row in the table? If you need to delete a row, how do you do it without an unique id?

There are some scenarios where it might make sense not to have a primary key, but it's rare, and you should have a clear reason as to why you're excluding it.

So, short answer: no, it's not ok.

Activity icon

Replied to Mass Assignement Laravel

@jokerdz The primary key is unique. In almost all cases, you want the database engine to auto increment this value for you. Otherwise, it is your responsibility to ensure that every table row has its own unique number. Which is a lot of unnecessary work that you don't want.

So, where is this value of 12222 coming from? just some random number you made?

Also, you're missing an apostrophe in your code where you're setting the $data variable. The IDFournisseur is missing the preceding ' -- mostly likely a typo here, as your code would terminate with an error otherwise.. but thought it is worth mentioning

If this is really want you want, make sure your Fournisseur model has the following:

protected $primaryKey = 'IDFournisseur';

public $incrementing = false;
Activity icon

Replied to Mass Assignement Laravel

@jokerdz You say that IDFournisseur is the primary key? If that is the case, you shouldn't be setting it. Instead, it should be set to Auto-incrementing (->bigIncrements()) -- but the primary key is usually named just 'id'.. so maybe you meant it is supposed to be the foreign key?

If you DO have it set as your primary key, why are you trying to assign it yourself?

Showing your fournisseurs table migration file would help.

Nov
18
1 week ago
Activity icon

Replied to Cannot Override The QUEUE_CONNECTION In Feature Testing

@untymage What does dd(config('queue.default')); return when you run it directly within your test? (not your controller)

Activity icon

Replied to Cannot Override The QUEUE_CONNECTION In Feature Testing

@untymage Did you check config/queue.php to make sure you didn't hardcode the default value? or still using QUEUE_DRIVER?

Activity icon

Replied to Cannot Override The QUEUE_CONNECTION In Feature Testing

@untymage Also check your config/queue.php and make sure you have:

'default' => env('QUEUE_CONNECTION', 'sync'),

Earlier versions of Laravel used QUEUE_DRIVER

Nov
17
1 week ago
Activity icon

Replied to How To Count Laravel Log In A Day?

@newlearner2 You could consider using Bugsnag. It'll record all your errors and the frequencies, along with a bunch of other useful information.You then have the option of completely ridding yourself of the log file, if you desire. It also has different settings, but by default it'll only notify upon the first occurrence of an error, which is what you're looking for. You can also configure your Bugsnag project to post to Slack.

https://docs.bugsnag.com/platforms/php/laravel/

Activity icon

Awarded Best Reply on Laravel Migration Big Integer DropForeign Key

@murilo Since you changed users.id to use bigIncrements, you need to also make your foreign key on your user_infos.user_id bigInteger to match the type:

	$table->bigInteger('user_id')->unsigned();
	$table->foreign('user_id')->references('id')->on('users');

Activity icon

Replied to Is `Builder` Class Considers As `Bloater`?

Well, Builder isn't too bad as it sticks closely to the data layer.

Eloquent (which uses Query Builder), on the other hand, could be considered a much larger violator of principals. Active Directory in general is considered a violation. So, in comparison, Builder is closer to separating concerns.. but again, these are choices you need to make. If you are a sole developer on a project, you're free to decide to use whatever you wish. If you work in a team, then everyone needs to sit down and decide what to stay consistent with.

Personally, I'm quite happy to use Eloquent in most cases, as the convenience it provides can't easily be ignored. I have the luxery of deciding to use it, and since I'm comfortable and experienced, I feel the reward is much greater than the potential pitfalls. Eloquent can't do everything, so in those cases, I drop down to using Builder, for complex queries, for example. I'd usually place all the complex query code inside its own Query Object that uses Builder.

Activity icon

Replied to Is `Builder` Class Considers As `Bloater`?

@pooladvand In the strictest sense, yes, it would be considered a "bloater", "god object", "violator of SRP principle", or whatever else you want to call it.

If you want to be a purist, you're not forced to use it. You can write your own PDO code and/or use a data mapper pattern... but your life will likely be much more miserable.

There are exceptions to every rule, and sometimes these rules needed to be bent/broken in the sake of of incredible convenience and time saving.

The choice is yours.

Activity icon

Replied to Laravel Migration Big Integer DropForeign Key

@murilo Since you changed users.id to use bigIncrements, you need to also make your foreign key on your user_infos.user_id bigInteger to match the type:

	$table->bigInteger('user_id')->unsigned();
	$table->foreign('user_id')->references('id')->on('users');

Nov
15
1 week ago
Activity icon

Replied to How To Return Response Json In Blade View

@emfinanga

public function customer(){

    $customer=Customer::All();

    if (request()->expectsJson())
	    return response()->json($customer);

     $customer_agent=CustomerAgency::All();

     return view('customers.index',compact('customer','customer_agent'));
    }
Activity icon

Awarded Best Reply on Getting The Count Of All Users In All Views

@mahmoudmonem sounds like you might be looking for shared view data:

View::share('productcount', Product::count());

To further reduce the queries, consider caching the count and only update each hour(or whatever suitable interval)

https://laravel.com/docs/8.x/views#sharing-data-with-all-views

Nov
14
1 week ago
Activity icon

Replied to Append Custom Data To Model Output

@msaied

return Appointment::select(['title','start'])->get()->map(function($appointment) {
   $appointment['url'] = config('app.url') . "/show/{$appointment->id}";

   return $appointment;
});

You could also consider making an accessor on your model and then appending it, so it is always available when you cast to an array or json:

Appointment.php


protected $appends = ['url'];

public function getUrlAttribute()
{
	return config('app.url') . "/show/{$this->id}";
}

https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json

Activity icon

Replied to Getting The Count Of All Users In All Views

@mahmoudmonem sounds like you might be looking for shared view data:

View::share('productcount', Product::count());

To further reduce the queries, consider caching the count and only update each hour(or whatever suitable interval)

https://laravel.com/docs/8.x/views#sharing-data-with-all-views

Activity icon

Replied to Laravel 8 Storage::delete (file) Return False

@rod2rick I think the problem here is that you are saving directly to your public folder, but using the Storage Filesystem to try to delete it (thru the Storage Facade)

So, you're manually storing to the public folder, but trying to delete it thru Storage.. so when you call Storage::delete(), it'll actually be looking for the file within /storage/app/public/public/uploads/avatars (if you have public set as your default disk)

You should really consider storing the avatars to the Storage filesystem instead of directly saving them to the public folder. Something like this instead:


$resizedIage = Image::make($avatar)->resize(500, 500);

Storage::disk('public')->put("avatars/{$filename}", $resizedImage);

Then you should be able to delete it with the Storage method.

Nov
11
2 weeks ago
Activity icon

Replied to Always Something Breaking When Using Laravel * Dependency Hell *

@niran Laravel 5.8 was released on Feb 2019, so it wasn't "a few years" ago. I've been using the framework for long before 5.8, so I don't know what you're talking about.

In the 5.8 documentation it shows installing using a version constraint:

composer create-project --prefer-dist laravel/laravel blog "5.8.*"

Or if you used the Laravel installer, it would have entered it for you.

So, I don't understand what you mean by saying that dev-master was "all there was".. can you explain further?

I can appreciate the notion that you didn't understand composer as much back then, we all start off somewhere and need to learn, but again, it's no fault of Laravel's that you required the dev-master branch.

Regardless of HOW you did this, I've explained how you need to resolve it. Change your composer.json to require a non-breaking version range, such as ^8.0 (if you want to be running on the latest) and then work out the conflicts one at a time until you've satisfied all errors.

Another option might be to look into Laravel Shift. I've never used it, but I've heard a lot of developers have. Maybe they can sort out the mess.

Nov
10
2 weeks ago
Activity icon

Replied to Always Something Breaking When Using Laravel * Dependency Hell *

@niran

when we started using Laravel we used Laravel 5.8, but the package was named dev-master

This is the source of your self-inflicted issues. You shouldn't require dev-master because every time you install/update via composer, you're going to be pulling in all the latest commits.

Laravel is not to blame here.. if you're using Laravel 5.8, then you should require 5.8.*, then you won't end up breaking your application and avoiding dependency hell.

I'd pick a stable tagged version of Laravel, and work at fixing all your dependencies from there. Then the framework will only update when you specifically bump your version number in composer.json.

Otherwise, if you want to lock your framework at your current dev-master commit, you could require the specific commit hash....

Laravel/Laravel:dev-master#3d7a5075e7db93a7df89c983c95d9016f448d3f9

Oct
29
3 weeks ago
Activity icon

Replied to Can't Run Laravel Horizon, Error In Laravel\Horizon\ProvisioningPlan::__construct()

@astersnake

The second parameter to that method should be an array of your configured environment for your queue workers. It gets this information from your config/horizon.php under the environments key.

If your configuration is set, open up thinker and try this:

 config('horizon.environments')

If that doesn't return anything, clear your config cache and try again: php artisan config:clear

Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'price' Cannot Be Null

@geordiejackson Since you are including the HasFactory trait, I assume you have a factory for the model. Another test you could try is something like this within tinker:


YourModel::factory(['price' => 0])->create();   // this should create a row in your database table

$model = YourModel::factory()->make();

unset($model->price); // to make sure its not set

$model->save();   // if this works, then there is nothing wrong with your database. It must be your application request


Activity icon

Replied to SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'price' Cannot Be Null

@geordiejackson Did you try disabling ConvertEmptyStringsToNull as an experiment?

Have you opened developer tools within the browser and inspected what is actually sent in the request?

Activity icon

Awarded Best Reply on Laravel 8 Installation

@amitshrestha221 my guess it that you are running PHP 7.2.x when Laravel 8 requires PHP 7.3+

Oct
28
4 weeks ago
Activity icon

Replied to Laravel 8 Installation

@amitshrestha221 my guess it that you are running PHP 7.2.x when Laravel 8 requires PHP 7.3+