Member Since 4 Years Ago
835 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.
Replied to Can You Use {id} For Some Logic And {slug} For Others?
You can not call two controller methods in one request. If you need that additional data then it has to be returned by one controller. If that is something that is shown on multiple pages than you can use https://laravel.com/docs/master/views#sharing-data-with-all-views
Replied to How Can I Get Last Two Query With Relationship
You need to append get()
at the end.
public function hasLastopup(){
return $this->hasMany('App\game_id','game_id','game_id')->latest()->take(2)->get();
}
But be aware that relationships should not contain that kind of logic. You should only have return $this->hasMany('App\game_id','game_id','game_id')
and then when you call you add what you need $x->hasOneWallet()->latest()->take(2)->get()
;
Replied to How To Add Another Field Like Email Verified To User
If we discard that this is global only on login solution, it looks appealing and you can not forget to include it like route specific middleware.
Replied to Laravel, Vue And SPA, Episode 11 ?
Maybe he is referring to where should you save that token so the frontend knows about it and stuff like that. We can only guess. Lately he is always opting for easier solution. Either he is tired of programming and overkill implementations or cause it is simpler to explain.
Replied to How To Add Another Field Like Email Verified To User
While answering your question vaporised out of my brain. Guess I'm tired. Middleware would be easiest way to achieve what you asked, and maybe best way.
Replied to How To Add Another Field Like Email Verified To User
Laravels out of the box email verification implies that you have email_verified_at
column in your users table. Which means that you will have your timestamp once user verifies his address. So no need to do anything like you asked.
Replied to Separate Controller Methods Seem To Be Messing With One Another
@bigweld86 like @gazd1977 answered. But I would suggest that you add some prefix to your admin.attributes.edit
route and maybe even suffix.
Cause I do not know if you wrapped in some group which you haven't disclosed here, but make full route something like
'/admin/attributes/{id}/edit'
// or
'/admin/attributes/{attribute}/edit' // to have model binding
Awarded Best Reply on Separate Controller Methods Seem To Be Messing With One Another
Route::group(['middleware' => ['guest:api', 'cors']], function () {
/**
* Grouped Routes for Attributes
*/
Route::group(['prefix' => 'attributes'], function() {
Route::get('/frontend-types', 'Admin\[email protected]');
Route::get('/{id}', 'Admin\[email protected]')->name('admin.attributes.edit');
});
});
Reorder routes cause order matters.
Replied to Separate Controller Methods Seem To Be Messing With One Another
Route::group(['middleware' => ['guest:api', 'cors']], function () {
/**
* Grouped Routes for Attributes
*/
Route::group(['prefix' => 'attributes'], function() {
Route::get('/frontend-types', 'Admin\[email protected]');
Route::get('/{id}', 'Admin\[email protected]')->name('admin.attributes.edit');
});
});
Reorder routes cause order matters.
Replied to Can You Use {id} For Some Logic And {slug} For Others?
You can create model called SlugJob
or something like that and have it extend Job
model. Overwrite $table
property and set it to (I guess) protected $table = 'jobs';
. After that overwrite on SlugJob
:
public function getRouteKeyName(): string
{
return 'slug';
}
Then for routes where you want to use slug
type hint SlugJob
and where you want to use id
type hint Job
.
That should do it until L7 is out.
P.S. Remove getRouteKeyName
method from Job
model.
Replied to Mocking Cashier Methods
I'd be interested to know more please.
It makes sense to me to have that kind of test if you can somehow create one test and let it test all routes on your app, but that gets messy very fast. If not then I would discard it. I've had similar approach when I started testing but then when something changes you have to fix same issue in multiple places since you will certainly add a test to see what happens when you have data in that invoices
method.
Lately I've stopped writing tests that prove negative statements cause it is:
Example for this istest_guest_can_not_access_some_url
. That is guarded by middleware which I do not own and there is no point for me to test it since it is a built in feature which if it had any issues someone would have caught it by now and fix it if we take into account how many people use same framework.
I know every company says in their ads that they want TDD, but the truth is that they do not care about that and they want you to do as much as possible as fast as possible. That mostly comes down to cutting test time (writing/maintaining) since that is nothing business side of company cares about. They just want less bugs and more features.
There really isn't any logic in that method that warrants testing, as it's not mine. But I would like to a test to make sure that the route is available and is returning a view and a 200.
The way you've picked then breaks the rule Do not mock what you do not own
. You do not own that billable trait which provides you with invoices
method, and you do not own User
model cause it ships with the framework, and you just mocked it.
That is why you should go with a service class or repository so you can mock since you will be introducing that class. Even if it is a class with one method that calls that same logic you have in your controller. I guess I should not point out what improvements does it bring to the code if you introduce a new class to handle that case.
Is it that this feel more like a unit test? I guess as it's a controller method, I thought this was really the only to way to test it.
There is no clear line what is unit and what is feature test. I guess that unit way to test this if you wrote something like this:
public function test_can_not_come_up_with_a_name_at_this_moment(): void
{
$controller = new SomeController();
$user = new User();
$response = $controller->index($user);
$this->assertSomething($response);
}
The code above would be a living hell if that controller or method gets complicated as they tend to in real life. That is why it feels to me more as feature test since you are accessing it as user of that application would, from outside. And when you access it from outside you trigger a bunch of features which then more feels like a feature test. That way you cover more ground.
What I think is that it makes sense to have unit test if you are building a calculator class, cause everything is probably contained within one class and it is transparent cause result depends directly on what you pass to it. If you do not have that kind of code then you are better of with feature test, since they are easier to write. You have your route, you know which data you need to send via request and you know what changes that request caused in the database. If you have any events, just assert that event was fired and write separate feature test for listeners that wait for that event.
Hope all this makes any sense, I'm still struggling to write any articulate text in english.
Replied to Eloquent With, WithCount Gives 12 As Total Records But The Function With Groupby On Date Gives 9
@princeoo7 this episode should probably better explain that I could ever do in forum post https://laracasts.com/series/whats-new-in-laravel-5-5/episodes/20
Watch it and then try again. If you have any issues after that you can ping back.
Replied to Mocking Cashier Methods
I think that having that specific feature tests which test tiny portions of app just complicate maintenance later on. But glad you found a solution.
Awarded Best Reply on Mocking Cashier Methods
Then create UserMock
which extends User
model and just put empty invoices
method. But that is a pretty empty test if you do not care what main feature of that endpoint does.
Yeah, that is the correct syntax but you then need to create a partial mock of the user and it all depends how do you resolve
that user from the app.
Replied to Eloquent's MorphedByMany Method
Have you guys tried something like this?
class Taggable extends Model
{
// here you can define relationship to polymorphic model
}
class Tag extends Model
{
public function taggables(): HasMany
{
return $this->hasMany(Taggable::class);
}
}
Replied to Carbon Fails In Job Queue
Is there a way to run jobs without using terminal?
That is not a point. You just should pass the value you need to the queued job like in this example $request->date_wanted
and not requesting that object from IOC. I've never tried but maybe if you pass $request
instance to the constructor of that queued job then maybe Laravel will serialise it properly and you'll have access to your date_wanted
.
Here are possible solutions for you to pick:
new NameOfYourQueuedJob($request)
use Illuminate\Http\Request;
class NameOfYourQueuedJob
{
public $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function handle()
{
$dateWanted = $this->request->date_wanted;
$dateObject = Carbon::createFromFormat('m/d/Y', $dateWanted)->format('Y-m-d');
}
}
Or if you only pass the value you need from request:
new NameOfYourQueuedJob($request->date_wanted)
class NameOfYourQueuedJob
{
public $dateWanted;
public function __construct(string $dateWanted)
{
$this-> dateWanted = $dateWanted;
}
public function handle()
{
$dateWanted = $this->dateWanted;
$dateObject = Carbon::createFromFormat('m/d/Y', $dateWanted)->format('Y-m-d');
}
}
Looks like you do not have much experience with passing object and asking IOC to resolve you one. I know there are tutorials on Laracasts about that so check them out.
Hope this helps and that you will listen now to what I'm saying and we can close this issue.
Replied to Attaching BelongsToMany Records After Submitting With Axios From Vue Component
You are very welcome 👍🏻
Replied to Attaching BelongsToMany Records After Submitting With Axios From Vue Component
submitForm()
{
axios.post('/rams', {
prelim_id: this.prelim.id,
user_id: this.user.id,
client_id: this.client_id,
job_no: this.job_no,
site: this.site,
description: this.description,
tasks: this.selected_tasks.map(task => task.id)
})
.then((response) => {
window.location.href = '/rams';
})
.catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors
}
});
}
Maybe something like this?
Awarded Best Reply on Attaching BelongsToMany Records After Submitting With Axios From Vue Component
Are you sure that you are sending something like following to attach()
:
$rams->tasks()->attach([
1,
2,
]);
You are probably sending whole objects instead of array of ID's which should be attached.
Replied to Attaching BelongsToMany Records After Submitting With Axios From Vue Component
Cmon hurry up back, I'm eager to find out 🤣
Replied to Attaching BelongsToMany Records After Submitting With Axios From Vue Component
Are you sure that you are sending something like following to attach()
:
$rams->tasks()->attach([
1,
2,
]);
You are probably sending whole objects instead of array of ID's which should be attached.
Replied to App.js Smaller On Production Server
If everything works then no. Many reasons can produce smaller size files.
First of all compression which you probably have turned on on production server while it is not on development environment.
When you run npm run prod
file gets minified so it also contributes to smaller size.
And so on...
Replied to How To Return Update Result As Json Object
This method is a great example where you can obviously benefit from defensive programming.
public function update(Request $request, $id)
{
$imageSearch = Gallery::findOrFail($id);
$file_image = $request->file('imageFile');
$file_thumbnail = $request->file('thumbnailFile');
$input = $request->all();
if (!$file_image || !$file_thumbnail) {
// or return some response
throw new \Exception('error');
}
$fileName = $file_image->getClientOriginalName();
$thumbName = $file_thumbnail->getClientOriginalName();
$path_images = 'images';
$path_thumbnail = 'thumbnails';
if (!$file_image->move($path_images, $fileName) || !$file_thumbnail->move($path_thumbnail, $thumbName)) {
// or return some response
throw new \Exception('error');
}
$input['image'] = '/' . $fileName;
$input['thumbnail'] = '/' . $thumbName;
$input['name'] = $request->name;
$input['species_id'] = $request->species;
$input['tag'] = $request->tag;
$input['patreon'] = $request->patreon;
$update = $imageSearch->update($input);
return response()->json([
'update' => $update,
'message' => 'Image has been Updated',
]);
}
Replied to Mocking Cashier Methods
Maybe best approach if you want to test it like that is to extract a service class or repository class and mock that service/repository. That way you own that class and can mock it without any issues. That gives you reusability and more control than what you have with built in Cashier methods.
Replied to Mocking Cashier Methods
Then create UserMock
which extends User
model and just put empty invoices
method. But that is a pretty empty test if you do not care what main feature of that endpoint does.
Yeah, that is the correct syntax but you then need to create a partial mock of the user and it all depends how do you resolve
that user from the app.
Replied to Eloquent With, WithCount Gives 12 As Total Records But The Function With Groupby On Date Gives 9
Checkout https://laravel.com/docs/5.7/eloquent-resources#writing-resources
I would not do grouping on the backend cause that is more presentation layer requirement but move it to frontend.
Replied to How To Combine Socialite + VueJS SPA
Number 3 is my vote if having blade for that feature is not acceptable.
Replied to 422 (Unprocessable Entity) Error On Ajax Request
You just need to send all fields that you've specified in your validation rules to get passed 422. That is absolutely normal 422 when validation fails.
Replied to Best Practices For CRUD Model
If I understand correctly, create ProjectCaseInputValueController
and within index
method return all your input values
.
Then deleteAllProjectByUser
becomes UserProjectController
with destroy
method.
Or you can maybe even go with UserProjectBulkController
with destory
method. Not a good solution but if that is what you are happy with then fine by me.
Replied to Best Practices For CRUD Model
functions within those controllers that don't belong to any model
Please elaborate a bit more cause I'm not sure what you are referring to.
Replied to Mocking Cashier Methods
I assume that you have correct pk_test and sk_test for Stripe in your testing environment. If so then you can put those keys in your development environment and create a subscription. Now when you did everything from the browser create a factory for Subscription model which will contain that specific Stripe ID while doing everything through browser. Then in your test you create a user and create subscription and do what you have in test right now.
That is the easiest way. Mocking can be also easy. You can save to a file what CurlClient returns and pass that as a return value to the mock. So you will always receive response that is valid for that test. You can mock even before, but it all depends on your use case and the level of details you want to test/assert.
Replied to Coverting From Jquery To Javascript
fetch('/pagination/fetch_browsergames_data?page='+page)
.then(function (data) {
document.querySelector('#games_content').innerHtml = data;
var lazyLoadInstance = new LazyLoad({
elements_selector: ".lazy"
// ... more custom settings?
});
document.querySelector('.page-loader').classList.add('page-loader-hidden');
});
Replied to CRUD Update With Random Entries
I think I do but you didn't understand me what I was trying to point to. But that is my English limitation. Anyway if you are happy with that answer all good.
Replied to Coverting From Jquery To Javascript
Or are you just looking for someone to do the job for you?
😂
Harsh but true.
Replied to Return View Or Redirect From Private Method
Then why don't you use policies?
https://laravel.com/docs/5.7/authorization#creating-policies
Replied to CRUD Update With Random Entries
If you are going to use it once than OK, but you can create class Coordinates
with static method named generate()
and use it where ever you like.
Here is if you need it to be limited to 12 hours and 60 minutes and seconds.
vsprintf('%s,%s%s%s', array_map(function ($array) {
return str_pad(rand($array[0], $array[1]), 2, '0', STR_PAD_LEFT);
}, [
[44, 45],
[0, 11],
[0, 59],
[0, 59],
]));
Ofc it is a quick solution which you can improve.
Awarded Best Reply on CRUD Update With Random Entries
vsprintf('%s,%s', [
rand(44,45),
rand(0, 999999)
]);
// or
rand(44000000, 45999999)/1000000;
You can use mt_rand()
also.
Replied to CRUD Update With Random Entries
vsprintf('%s,%s', [
rand(44,45),
rand(0, 999999)
]);
// or
rand(44000000, 45999999)/1000000;
You can use mt_rand()
also.
Replied to Best Practices For CRUD Model
https://www.youtube.com/watch?v=MF0jFKvS4SI
Watch that video. Same applies to API approach.
Replied to Problem With Carousel In Svg In Chrome
Then I'm afraid that there is no help. Why don't you use transparent PNG? Does it have be SVG?
Replied to CRUD Update With Random Entries
Show us an example of the current and desired values and when you want those values to be updated. Telling us over and over again that you want random data without examples make it hard to help.
Replied to How Bad Is Lavarel Code Rot In Comparison To Raw Php?
Laravel has LTS versions which receive updates for 2 years so maybe your impression is bit skewed. I think that code rot is far more present in raw php than with frameworks.
Replied to Carbon Fails In Job Queue
That should then imply that value you are passing is null
cause of the same message. So that then relates to request not having that value, which is due to not having requests when you run queue jobs from terminal.
Lifecycle of request ends when you get response from the browser. It can not extend itself to queued job which is later on started from terminal by some supervisor or what ever you are using.
Replied to Problem With Carousel In Svg In Chrome
Have you tried traditional options like visibility, opacity, display?
Replied to Refactor: Request In Controller & Calling Other Methods, Any Ideas?
That is always worth it.
Replied to Problem With Carousel In Svg In Chrome
I'm sure if you open it in Safari that you will have totally different situation.