4,200 experience to go until the next level!
In case you were wondering, you earn Laracasts experience when you:
Earned once you have completed your first Laracasts lesson.
Earned once you have earned your first 1000 experience points.
Earned when you have been with Laracasts for 1 year.
Earned when you have been with Laracasts for 2 years.
Earned when you have been with Laracasts for 3 years.
Earned when you have been with Laracasts for 4 years.
Earned when you have been with Laracasts for 5 years.
Earned when at least one Laracasts series has been fully completed.
Earned after your first post on the Laracasts forum.
Earned once 100 Laracasts lessons have been completed.
Earned once you receive your first "Best Reply" award on the Laracasts forum.
Earned if you are a paying Laracasts subscriber.
Earned if you have a lifetime subscription to Laracasts.
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.
Earned once you have achieved 500 forum replies.
Earned once your experience points passes 100,000.
Earned once your experience points hits 10,000.
Earned once 1000 Laracasts lessons have been completed.
Earned once your "Best Reply" award count is 100 or more.
Earned once your experience points passes 1 million.
Earned once your experience points ranks in the top 50 of all Laracasts users.
Earned once your experience points ranks in the top 10 of all Laracasts users.
Replied to Refactoring Code
You could simply extract a method such as:
protected function funcName()
{
return [
Category::select('id', 'name')->get(),
Tag::select('id', 'name')->get()
];
}
and call it from your create and edit methods. e.g.:
public function create()
{
[$categories, $tags] = $this->funcName();
return response()->json([
'categories' => $categories,
'tags' => $tags,
]);
}
Your code will now be a bit DRYer.
Replied to Fillter By View Count Laravel
"Not working" is a bit vague.
What is not working? What results are you getting?
Replied to Undefined Variable: Data
In the edit function, all you want to do is pass the Todo
object to the blade for editing. So, your edit()
method should look something like:
public function edit(Todo $todo)
{
return view('layouts.edit')->with('todo', $todo);
}
Then your Todo
object is available in the blade.
NOTE: if you're working with a Todo
object, name the variable $todo
rather than $data
. A name such as $data
is vague, therefore poor programming practice.
Awarded Best Reply on Seeders - Pass Iteration To Factories
When you create a model using Client::factory()->create();
, you can pass in the field's data too and it will override the faker method in the factory. e.g.
Client::factory()->create(['name' => 'Client 1']);
will set the name to "Client 1".
So, if you create a loop in your seeder, you can do something like this:
foreach(range(1, 10) as $int) {
Client::factory()->create(['name' => 'Client ' . $int]);
}
and you'll have the data formatted the way you want. Knowing the data values you're working with in tests is not always a good idea though (!)
Do the looping in the seeder rather than trying to do it in the factory.
Replied to Seeders - Pass Iteration To Factories
When you create a model using Client::factory()->create();
, you can pass in the field's data too and it will override the faker method in the factory. e.g.
Client::factory()->create(['name' => 'Client 1']);
will set the name to "Client 1".
So, if you create a loop in your seeder, you can do something like this:
foreach(range(1, 10) as $int) {
Client::factory()->create(['name' => 'Client ' . $int]);
}
and you'll have the data formatted the way you want. Knowing the data values you're working with in tests is not always a good idea though (!)
Do the looping in the seeder rather than trying to do it in the factory.
Replied to Best Way To Read Config File Within A Service Provider
In the service provider, just use:
$this->mergeConfigFrom('path_to_your_config', 'your_key_name');
and it will add your config settings to config();
Replied to How To Destroy Records?
The route: Route::post
should be:
Route::delete
i.e. use the Route::delete method to initiate a delete request.
Awarded Best Reply on Route Not Working Target Class Does Not Exist
I can't reproduce the behaviour. It works fine for me - Laravel 8 fresh install.
Do you have any namespace set in your RouteServiceProvider?
Have you tried the new tuple syntax?
e.g.
Route::get('/admin', [DemoController::class, 'adminDemo']);
Route::get('/admins', [DemoController::class, 'adminDemo']);
Route::get('/users', [DemoController::class, 'adminDemo']);
Route::get('/user',[DemoController::class, 'adminDemo']);
Remembering to import DemoController
.
Replied to Route Not Working Target Class Does Not Exist
I can't reproduce the behaviour. It works fine for me - Laravel 8 fresh install.
Do you have any namespace set in your RouteServiceProvider?
Have you tried the new tuple syntax?
e.g.
Route::get('/admin', [DemoController::class, 'adminDemo']);
Route::get('/admins', [DemoController::class, 'adminDemo']);
Route::get('/users', [DemoController::class, 'adminDemo']);
Route::get('/user',[DemoController::class, 'adminDemo']);
Remembering to import DemoController
.
Replied to Route Not Working Target Class Does Not Exist
Have you tried php artisan route:clear
after making the changes?
Also, composer dump-autoload
is sometimes needed.
Replied to I Want To Display All Roles Who This User {id} Don't Have.
A simple way to do this is to extract the User's Roles from all Roles before passing the data to the blade for display.
i.e. Get a collection of all roles, a collection the user's roles and use $collection->diff()
to subtract the user's roles out.
$allRoles = Role::all();
$userRoles = User::find($id)->roles;
$unassignedRoles = $allRoles->diff($userRoles);
Then pass $unassignedRoles
into your blade. You'd have to adapt the code to suit the way you've done it, but that's one way. It will at least give you a workable solution until you sort out your Role/User relationships.
Awarded Best Reply on Multiple Arrays To Iterate Over
The best way to deal with this situation is to transpose
the arrays of data. i.e. swap rows and columns around.
You need a transpose()
method, which Laravel doesn't currently have, so you'll need to add it via a macro
.
In your App\Providers\AppServiceProvider
(or any other you may want to use), add this function:
Collection::macro('transpose', function () {
$items = array_map(function (...$items) {
return $items;
}, ...$this->values());
return new static($items);
});
Add use Illuminate\Support\Collection;
to the top of the file if Collection
hasn't been imported automatically.
This will add the transopse()
method to the Collection
class which you can use to transpose any collection of arrays passed in to it.
How to use
Firstly, turn your $request into a collection. e.g. $collection = collect($request->all())
or $request->input(), $request->validated() etc.
Then transpose the arrays:
$transposed = $collection->only(['description', 'priority', 'deadline' 'sub_budget'])->transpose();
The $transposed
rows should now be in the same order as they were input in the form - making them much easier to work with.
Replied to 3 Tables Many To Many Relationship How To Code With Eloquent
Many to many relationships are described here: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
So, Company belongsToMany
Task, and Task belongsToMany
Company.
Then do the same for Company - User and Task-User (depending on their specific relationships).
That way you'll build up all the necessary relations. You can then do all of the permutations in accessing models through their relations.
Replied to 3 Tables Many To Many Relationship How To Code With Eloquent
I'd say you'd need to break it down.
How many companies can a user belong to?
Is a task assigned to 1 company or to many?
i.e. find the relationships between each of the entities individually and build the relationships from there.
Replied to Argument 1 Passed To Illuminate\Database\Eloquent\Model Error
I would say the answer is in the question:
if I load model object from DB and do not use buffer problem solved
If your query is really taking too long, could you not just optimize your query?
Awarded Best Reply on Homestead 11 Download
If you follow the docs https://laravel.com/docs/8.x/homestead when you get to here:
git checkout release
type:
git checkout v11.0.4
instead.
If you have any problems using it, just go back to using release
as it's the latest stable version.
Replied to Homestead 11 Download
If you follow the docs https://laravel.com/docs/8.x/homestead when you get to here:
git checkout release
type:
git checkout v11.0.4
instead.
If you have any problems using it, just go back to using release
as it's the latest stable version.
Replied to How To Delete Laravel Form Using Get Method
To delete a database entry you need to use "DELETE" request method rather than "GET" or "POST". e.g.:
Route::delete('users/{user}', '[email protected]');
In your form, you need to set the form's "method" to "delete" but forms do not have a "delete" method available so you have to spoof it. So, in your form just add:
<input type="hidden" name="_method" value="DELETE">
Or as a shortcut, just add the blade directive:
@method('DELETE')
instead.
See: https://laravel.com/docs/8.x/routing#form-method-spoofing
Replied to Tailwind Part ✌🏻
In package.json, change "laravel-mix": "^5.0.1",
to "laravel-mix": "^6.0.0-beta.14"
and it might run OK.
Tailwaind 2 doesn't seem tp be fully compatible with laravel just yet - or at least it wasn't the last time I tried it.
Replied to Multiple Arrays To Iterate Over
The best way to deal with this situation is to transpose
the arrays of data. i.e. swap rows and columns around.
You need a transpose()
method, which Laravel doesn't currently have, so you'll need to add it via a macro
.
In your App\Providers\AppServiceProvider
(or any other you may want to use), add this function:
Collection::macro('transpose', function () {
$items = array_map(function (...$items) {
return $items;
}, ...$this->values());
return new static($items);
});
Add use Illuminate\Support\Collection;
to the top of the file if Collection
hasn't been imported automatically.
This will add the transopse()
method to the Collection
class which you can use to transpose any collection of arrays passed in to it.
How to use
Firstly, turn your $request into a collection. e.g. $collection = collect($request->all())
or $request->input(), $request->validated() etc.
Then transpose the arrays:
$transposed = $collection->only(['description', 'priority', 'deadline' 'sub_budget'])->transpose();
The $transposed
rows should now be in the same order as they were input in the form - making them much easier to work with.
Replied to How To Remove Some Packages / Vendor?
@obink You can use composer remove some-bundle/for-laravel
to remove the package but you'll have to delete any published assets manually.
TIP: if you use Git, always test packages in a new branch. If you like it, you can merge it in, if not you can delete the branch - you won't then have any files left to delete manually.
Replied to Laravel And Tailwind
If you run npm install tailwindcss postcss autoprefixer
in your terminal do you see any error messages?
I think that PostCSS requires Node to be a recent version (13 or 14 IIRC).
It might just be a case of updating Node on your system.
Awarded Best Reply on How To Add A Index On A Constrained Foreign Key
If you set a foreign key, it's set to an index automatically when the constrained()
method is added.
If you look in your database client and look for 'indexes' under 'structure' you should see something like this:
tablename_foo_id_foreign
Replied to Foreach And Loop
You don't need to use a counter in a foreach loop.
Firstly, make sure that you have the correct data to work with:
foreach ($user_positions as $user_position) {
dump($user_position, $user->id);
}
If that looks correct, then create new entries using:
foreach ($user_positions as $user_position) {
UserHasPosition::create([
'user_id' => $user->id,
'user_position_id' => $user_position,
]);
}
If you're updating entries use update
instead of create
or you could use updateOrCreate
if you're doing both.
Replied to How To Add A Index On A Constrained Foreign Key
If you set a foreign key, it's set to an index automatically when the constrained()
method is added.
If you look in your database client and look for 'indexes' under 'structure' you should see something like this:
tablename_foo_id_foreign
Replied to How Do You Use The Sync Function In A Multi Dimensional Array In Laravel
It's a while since I've done this but if I remember correctly, when you want to sync multiple records at the same time, you need to pass in a list of the records' Ids.
e.g.
if($request->subjects) {
$subjectIds = collect($request->subjects)->map(function($subject) {
return $subject['id'];
});
}
Then sync using the Ids:
$user->subjects()->sync($subjectIds);
Or similar...
Replied to Requested Resource NOT Found (livewire/message)
Looking again, the error message is:
"The requested resource /livewire/message/frontend.view-product was not found on this server."
But it should be looking for:
"/livewire/message/frontend/view-product"
Note the slash instead of the dot in the view's path.
I suspect that the component's render()
method is where something is going wrong. It's looking for a view called frontend.view-product
rather than view-product
in the frontend
folder.
Anyway, that might be the clue you need to dig deeper.
Replied to Requested Resource NOT Found (livewire/message)
Instead of
<button wire:click.prevent="addToCart()"
You could try:
<form wire:click.prevent="addToCart()"
Only from memory, but I'm sure I had this problem and that's what it was. i.e. it was doing a submit when typing in the form fields.
Worth a try anyway. 👍
Replied to Need Some Feed Back On How This Works?...
The : SlugOptions
part of the method definition is just a typehint for the return type.
It means that the method must return a SlugOptions
object.
See: https://www.brainbell.com/php/type-declarations-hints.html#return-type
Awarded Best Reply on Update Php 7.3 To Version 7.4 With Mac
Ah, I've misunderstood what you're after.
PHP7.4 will be listed under php
as it's the latest version. It doesn't show up as [email protected]
Replied to Update Php 7.3 To Version 7.4 With Mac
Ah, I've misunderstood what you're after.
PHP7.4 will be listed under php
as it's the latest version. It doesn't show up as [email protected]
Replied to Update Php 7.3 To Version 7.4 With Mac
If it's linked then you should already be using php7.4.
Replied to Update Php 7.3 To Version 7.4 With Mac
Try brew link [email protected]
That works for me.
Replied to How To Avoid Duplicate Seeding?
@martinzeltin In your PostSeeder
you could do something like:
public function run()
{
$count = User::count();
for ($i = 0; $i < 50; $i++) {
Post::factory()->create([
'user_id' => random_int(1, $count),
]);
}
}
i.e. count the number of users and randomly assign their ids to posts.
This is OK for testing purposes.
Obviously, this relies on you having seeded the users table first!
Replied to How To Check Is Param Collection Or Object
How can I check if I passed something like:
User::find($id) or User::where('id', '!=', auth()->user()->id)->get()
The first one will return an object and the second one a collection.
It might be better to simply use a collection for both - then you won't need the conditional in your send()
method.
e.g. instead of using: User::find($id)
, use
User::whereId($id)->get();
This will return an Eloquent Collection (with only one result in it) so your method can be simplified to:
public function send($notification, Collection $users)
{
foreach ($users as $user) {
$this->create([
'user_id' => $notification['user_id'],
'foruser_id' => $user->id,
'type_id' => $notification['type'],
'info' => $notification['info'],
]);
}
}
If $users is empty, the foreach() won't run.
NOTE: the typehint of Collection (Illuminate\Database\Eloquent\Collection) in the parameters to ensure only Collections are accepted.
This way you can avoid all the if()
and else()
checks and keep the code nice and clean.
Replied to Lifetime Subscription: When Does It End?
Lifetime subscription: when does it end?
I think I prefer not knowing to be honest! 😳
Replied to Problem When Saving Data In Multistep Form.
@seaniz If you use $request->session()->put('responses', $responses);
the put()
method will overwrite the session data each time.
It would be better to create an array and push()
your responses onto it each time.
e.g. in storeFirstPage
try:
if ( ! $request->session()->exists('responses')) {
$request->session()->put('responses', []);
}
$request->session()->push('responses', $responses);
Or similar (this is off the top of my head!)
And remember to $request->session()->forget('responses');
after you save them.
Replied to Manipulate Request Parameters
So you want to be able to do the names
check independently of any other validation you're doing and on more than one form?
This sounds like a good use case for an Action
class. See: https://stitcher.io/blog/laravel-beyond-crud-03-actions
i.e. create an Action
class with your code in it that can be called whenever needed.
Replied to SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'price' Cannot Be Null
I've had another look at this and can't see anything wrong.
In Tinker I did:
$p = App\Models\Product::factory()->make();
and got
App\Models\Product {#4362
name: "doloribus",
price: 0,
}
then
>>> unset($p->price);
>>> $p
=> App\Models\Product {#4362
name: "doloribus",
}
>>> $p->save();
=> true
>>> $p
=> App\Models\Product {#4362
name: "doloribus",
updated_at: "2020-10-29 15:00:39",
created_at: "2020-10-29 15:00:39",
id: 17,
}
>>> $p->refresh();
=> App\Models\Product {#4362
id: 17,
name: "doloribus",
price: "0.00",
created_at: "2020-10-29 15:00:39",
updated_at: "2020-10-29 15:00:39",
}
at the save()
stage, the database set the price to "0.00" as expected.
Replied to SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'price' Cannot Be Null
I've just tried this with Laravel 8 using MySQL 8 and it works fine.
Could it be your database settings rather than a problem with the code?
Replied to Manipulate Request Parameters
I would use a FormRequest
class. See: https://laravel.com/docs/8.x/validation#form-request-validation
and in the form request class, use the prepareForValidation()
method to manipulate the request fields (e.g. exploding the names
field) and then let the validation run as normal - with the validation in the rules()
method.
e.g.
protected function prepareForValidation()
{
// Manipulate request fields here
}
public function rules()
{
return [
// Set validation rules here
];
}
public function validated()
{
// Post validation manipulation can be done here if required
}
Replied to SQLSTATE[23000]: Integrity Constraint Violation: 1048 Column 'price' Cannot Be Null
Have you tried
->default("0")
i.e. add quotation marks to ensure that the 0 is saved as a string.
You could try changing:
$table->longText('content')->nullable();
to
$table->text('content')->nullable();
Unless you really need a longText field - they require a lot of memory.
Otherwise, you could increase the size of memory_limit
in you php.ini file to ~1024M (or whatever is needed).
Replied to Wrap Any Assoc Array In Collection
You can update the array using:
$tagsArray = $collection->get('tags');
data_set($collection,'tags', [$tagsArray]);
Where $collection == the name of your collection.
Awarded Best Reply on Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.
It looks like you've been trying to search for $request['name']
whereas your search field is passed as $request['search']
;
Just change your method to:
public static function search($request)
{
$categories = Category::query();
if (isset($request['search'])) {
$categories = $categories->where('name', 'like', '%'.$request['search'].'%');
}
return $categories->paginate(1);
}
and you should be there.
You may also need to put:
Route::resource('categories', 'CategoryController');
Route::post('categories', [CategoryController::class, 'index']);
In your routes too as you're posting to an index
method. Which is actually another no-no!
Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.
It looks like you've been trying to search for $request['name']
whereas your search field is passed as $request['search']
;
Just change your method to:
public static function search($request)
{
$categories = Category::query();
if (isset($request['search'])) {
$categories = $categories->where('name', 'like', '%'.$request['search'].'%');
}
return $categories->paginate(1);
}
and you should be there.
You may also need to put:
Route::resource('categories', 'CategoryController');
Route::post('categories', [CategoryController::class, 'index']);
In your routes too as you're posting to an index
method. Which is actually another no-no!
Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.
Sorry, I was using a collection to test this rather than the request Object.
Try changing the method to:
public static function search($request)
{
$categories = Category::query();
if (isset($request->name) || isset($request['name'])) {
$categories = $categories->where('name', 'like', '%'.$request['name'].'%');
}
return $categories->paginate(2);
}
This should work with either the request object or the request->all() array.
Replied to Method Illuminate\Database\Eloquent\Collection::paginate Does Not Exist.
You shouldn't have a collection when you're calling the paginate method.
Have you copied and pasted my method exactly?
i.e.
public static function search($request)
{
$categories = Category::query();
if (array_key_exists('name', $request)) {
$categories = $categories->where('name', 'like', '%'.$request['name'].'%');
}
return $categories->paginate(1);
}
Note: I've changed collect() to array_key_exists() - as you're passing in an array rather than a collection.