3,320 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 Redirect Link Is Not Working
You are using the Route::resource
method and also using a route that would be created by that method:
Route::group(['middleware' => 'student'], function () {
Route::get('/student/index', '[email protected]');
});
// the above route will automatically be created by the below resource method
Route::Resource('/student', 'StudentController');
Because the Resource
route is appears after the initial one, it will take precedence. So, my guess is the 404 has something to do with the student
middleware, since the Resource
created route does not have that applied but your initial custom route does. If you want to only apply that middleware to that one route try this instead:
Route::group(['middleware' => 'student'], function () {
Route::get('/student/index', '[email protected]');
});
Route::Resource('/student', 'StudentController');>except([
'index',
]);
Also, I think @nomguy 's suggestion is a good option for you here for student
, admin
, etc.
You can read more about this subject in the docs: https://laravel.com/docs/5.8/routing#route-group-prefixes
Replied to Redirect Link Is Not Working
This may be an issue with your web/routes
file. Can you share it please?
Replied to Validation Of Input Fields Of Custom Tabs In Javascript
There are a couple of options you can consider here. One would be to send a variable along with the request to the server that indicates which tab was active at the time of submission. Then, use this info in your validation logic to only validate the appropriate fields. That honestly feels a bit hacky, but outside of creating a separate form for each of the tabs, it might be the best way to go.
Replied to Testing Auth Route Option
Here is where the feature is implemented in the Framework: https://github.com/laravel/framework/blob/bbb7bbf6e5b29ca6cad083f317681c70ee0c0b42/src/Illuminate/Routing/Router.php#L1149
The method is below. While I couldn't find any tests in the Framework for this, perhaps that's because the code simply uses the null coalescing operator to determine if the particular routes are explicitly excluded in the options array and if not, it adds the routes.
public function auth(array $options = [])
{
// Authentication Routes...
$this->get('login', 'Auth\[email protected]')->name('login');
$this->post('login', 'Auth\[email protected]');
$this->post('logout', 'Auth\[email protected]')->name('logout');
// Registration Routes...
if ($options['register'] ?? true) {
$this->get('register', 'Auth\[email protected]')->name('register');
$this->post('register', 'Auth\[email protected]');
}
// Password Reset Routes...
if ($options['reset'] ?? true) {
$this->resetPassword();
}
// Password Confirmation Routes...
if ($options['confirm'] ??
class_exists($this->prependGroupNamespace('Auth\ConfirmPasswordController'))) {
$this->confirmPassword();
}
// Email Verification Routes...
if ($options['verify'] ?? false) {
$this->emailVerification();
}
}
So, it's pretty straightforward. That being said, this is an important thing to get right considering the security implications of a route being available when the developer may not realize it. I am considering adding a PR to fix that but I want to search a bit more to make sure the tests don't already exist.
Replied to Scrollspy Not Working
In the element your trying to apply the scroll-spy to, do have its ID set to navbarGenerations
like below.
<nav id="navbarGenerations" class="navbar navbar-light bg-light">
Also, there are some quirky rules about case-sensitivity with HTML and CSS, so if you already took care of the above issue, try changing the ID to something like: navbar-generations
in both the element and any required selectors.
Good luck!
Replied to How To Make Edit And Update Multi Select Form Value
What kind of issues are you having? Are there any errors? If so, please show the error messages or stack traces and that will make it easier to provide help.
Replied to Trying To Implement JWT But It Says Controllers Don't Exists, Laravel 5.8
Check out this section of the docs: https://laravel.com/docs/5.8/authentication#adding-custom-guards
I think this is what you are going for.
Replied to How To Get Files InLaravel Controller As Normal File Element By Using FilePond.js?
What does your AJAX look like?
Awarded Best Reply on 422 (Unprocessable Entity) // CreateError.js:16 Uncaught (in Promise) Error: Request Failed With Status Code 422
Hi @jet
It could be this:
let _this = this
axios.post(this.url, data)
.then(function(res) {
const re = res.data
_this.personalInfo = data
_this.toggle();
})
.then(function(err) {
console.log(err)
})
Try using .catch
for the error catching block like this:
axios.post(this.url, data)
.then(function(res) {
const re = res.data
_this.personalInfo = data
_this.toggle();
})
.catch(function(err) {
console.log(err)
})
Also, it appears you are using es6, so you should be able to remove the _this
hack to grab the parent context with the arrow function, see below:
axios.post(this.url, data)
.then(res => {
const re = res.data
this.personalInfo = data
this.toggle();
})
.then(err => {
console.log(err)
})
Awarded Best Reply on Pulling Data From Two Tables As Array
If you were using the $store
variable as in the previous post it would probably look more like this:
<td><input type="text" value="
@foreach ($store as $pettycashitem)
{{ $pettycashitem->td_item_desc }}
@endforeach
You may want to start a new question thread with some more specific questions as this one is getting kind of unwieldy.
Replied to Pulling Data From Two Tables As Array
If you were using the $store
variable as in the previous post it would probably look more like this:
<td><input type="text" value="
@foreach ($store as $pettycashitem)
{{ $pettycashitem->td_item_desc }}
@endforeach
You may want to start a new question thread with some more specific questions as this one is getting kind of unwieldy.
Replied to 404 Not Found Laravel
It could be in the redirect of the controller below:
return redirect()->route('viewclaim',['id' => $id])->with('success','Claim Rejected By Regional Manager');
Do you have a named route called "viewclaim"? If you could show the applicable part of the routes/web
file for that route it would be helpful.
Replied to 404 Not Found Laravel
Can you show the controller code for one or both pertaining to those methods?
Replied to 404 Not Found Laravel
View the source of your page in the browser and inspect what the url output is for the two links.
Replied to Pulling Data From Two Tables As Array
Hi @bhhussain
I don't really follow. The Pettycashitem
s should not be available in the $pettycashhead
variable so I don't think you need to use the $store
variable to pass all of the Pettycashitem
s to the view.
Also, are you familiar with php loops
like for
or foreach
loops? Generally that is how you would iterate through and display the data. When I see things like print_r($store[2]->td_item_desc)
it leads me to believe that you are not using a loop. Laravel has some really nice helpers with loops when using Blade as well, check it out here: https://laravel.com/docs/5.8/blade#loops
Replied to Using A Policy With Scout
Sorry about that, per this comment on GitHub I thought you would be able to.
Replied to Using A Policy With Scout
Maybe a local query scope would make sense in this case: https://laravel.com/docs/5.8/eloquent#global-scopes
So something like:
// Article Model
/**
* Scope a query to only include only published articles.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePublished($query)
{
return $query->where('status', 'published);
}
Then you can do the following:
$articles = Article::published()->search($query_string)->orderBy('created_at', 'desc')->get();
And you can continue to use these scopes to shorten often used queries. So, if you want to set the default order of the articles, you can use another scope like this:
public function scopeOrdered($query)
{
return $query->orderBy('created_at', 'desc');
}
And that would shorten your query just a bit more and make it more readable, in my opinion:
$articles = Article::published()->ordered()->search($query_string)->get();
Replied to Pulling Data From Two Tables As Array
In your return
statement in the controller, it doesn't appear you are sending any to the view?
return redirect('accounts/pettycash')->with('success','Transaction created successfully!');
Previously you had something like:
return view('accounts.pettycash.print')->with('pettycashhead', $pettycashhead)->with('pettycashitem',$pettycashitem)->with('store',$store)->with(['key' => 'td_tran_no'])->with('arr', $arr);
Replied to How To Use With() When You Have The Relationship In A 3rd Table?
Is the name the of the model Categories
or Category
? If it is Category
then it should be:
$result = App\Models\Category::with('foods')->get();
Replied to How To Use With() When You Have The Relationship In A 3rd Table?
I just updated my answer, so please take another look. But to answer your question directly, you would do this:
// this query will contain all of the Categories, Subcategories and Foods.
App\Category::with('foods')->get();
// you can iterate through like this
foreach (App\Category::with('foods')->get() as $category) {
$category->foods; // all foods in category
$category->subcategories; // all subcategories in category
}
Replied to How To Use With() When You Have The Relationship In A 3rd Table?
I would set the relationships up like below. In this setup, the Category and Food models have many-to-many relationship, and therefore a pivot table will need to be created to manage that, and if you're following Laravel conventions that pivot table would be called categories_foods
. Then Category has-many
subcategories and the SubCategory belongs-to
the Category.
If you think about it, there is no need to have the Food
associated with Subcategory
as it would be redundant, since the Food already has a relationship with the Category
which owns the Subcategory
s.
Therefore you could achievecategories -> subcategories -> foods
in a variety of ways:
// get all of the subcategories for a category
App\Category::find(1)->subcategories;
// get all of the foods with their categories with Eager Loading
App\Food::with('categories')->get();
// get all of the categories with their foods with Eager Loading
App\Food::with('categories')->get();
// get all of the subcategories for a food (using the hasManythrough relation on the food model
App\Food::find(1)->subcategories;
// get all the foods of a certain subcategory
$foods = App\Food::with(['category' => function ($query) use (subcategory){
$query->whereIn(subcategory->id, $category->subcategories)
}])->get();
// Food Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model
{
/**
* Get the categories for the food.
*/
public function categories()
{
return $this->hasMany('App\Category');
}
/**
* Get all of the subcategories for the food
*/
public function subcategories()
{
return $this->hasManyThrough('App\Subcategory', 'App\Category');
}
}
// Category Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
/**
* Get the foods for the category.
*/
public function foods()
{
return $this->hasMany('App\Food');
}
/**
* Get the subcategories for this category.
*/
public function subcategories()
{
return $this->hasMany('App\Subcategories');
}
}
// Subcategory Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subcategory extends Model
{
/**
* Get the category this subcategory belongs to
*/
public function category()
{
return $this->belongsTo('App\Category');
}
}
Awarded Best Reply on Foreign Key Constraint Is Incorrectly Formed
Make sure the migration order is correct. Essentially, if the users
table is created before the roles
table in your migration order (which runs in order by the file name that includes the creation date), this could be causing your issue.
Check out this SO answer for more details: https://stackoverflow.com/a/45820046
Replied to Foreign Key Constraint Is Incorrectly Formed
Make sure the migration order is correct. Essentially, if the users
table is created before the roles
table in your migration order (which runs in order by the file name that includes the creation date), this could be causing your issue.
Check out this SO answer for more details: https://stackoverflow.com/a/45820046
Replied to Check If Specific Keys In Collection Has Value Or Not
How about something like this:
$filteredEmployees = $employees->reject(function ($value, $key) {
return $value['email'] !== null || $value['position'] !== null;
});
return $filteredEmployees->count() === $employees->count();
Replied to Pulling Data From Two Tables As Array
Thanks for sharing the whole controller. I now see that you are accepting Pettycashhead
as an argument to the store
method. So, you would want to remove the App\
part and there is no need hit the DB to find the correct Pettycashhead
as the correct one should have already been instantiated, so something you can probably just remove the below line (commented out):
// $pettycashhead = App\Pettycashhead::findOrFail($request->pettycashhead_id[$key]); not necessary
$pettycashhead->pettycashitem()->save($pettycashitem);
Replied to Pulling Data From Two Tables As Array
Try to leverage some of Laravel's relationship helpers:
if($request->td_qty[$key]) {
$pettycashitem = resolve(Pettycashitem::class);
$pettycashitem->td_item_desc = trim($name,'"');
$pettycashitem->td_qty = $request->td_qty[$key] ;
$pettycashitem->td_unit_price = $request->td_unit_price[$key] ;
$pettycashitem->td_tran_no = $new_id;
$pettycashitem->save();
// this assumes that the $request->pettycashhead_id[$key] is the id of the required Pettycashhead
$pettycashhead = App\Pettycashhead::findOrFail($request->pettycashhead_id[$key]);
$pettycashhead ->pettycashitem()->save($pettycashitem);
}
Replied to Pulling Data From Two Tables As Array
Ah, okay, I ready your second post, take a look at this SO thread, there seem to be quite a few ways to fix this: https://stackoverflow.com/questions/22615926/migration-cannot-add-foreign-key-constraint-in-laravel
If you are using Laravel 5.8 or higher, try jumping right to this answer: https://stackoverflow.com/a/55996747
Replied to Pulling Data From Two Tables As Array
Okay so in your pettycashitems
migration you would have to add the foreign key constraint like below:
Schema::create('pettycashitems', function (Blueprint $table) {
$table->bigIncrements('id');
$table->Integer('td_tran_no')->nullable();
$table->string('td_item_desc')->nullable();
$table->Integer('td_qty')->nullable();
$table->float('td_unit_price')->nullable();
$table->float('td_unit_amt')->nullable();
$table->date('td_bill_dt')->nullable();
$table->date('td_supp_name')->nullable();
$table->foreign('pettycashhead_id')->references('id')->on('pettycashheads'); // this line
$table->timestamps();
});
To link the Pettycashhead
with its Pettycashitem
s you can use one of Laravel's conveniencers like the save method, the associate method, etc. as opposed to using the DB facade and updating the foreign key manually.
But if you already have actual data in your DB, and not just testing data, you may have to go back and add this manually.
Replied to Pulling Data From Two Tables As Array
Did you add return
to both the Pettycashhead
and the Pettycashitem
model relationships? Also, what does your pettycashitems migration file look like? It would need to have the pettycashhead id as a foreign key (pettycashhead_id) in order for the relationship to work.
Replied to Pulling Data From Two Tables As Array
Couple of things, First, you are using the firstOrFail
method on the Pettycashitem
, this will only grab one record from the DB. Perhaps you want to use the all method?
// try changing this
$pettycashitem = Pettycashitem::where('td_tran_no', $pettycashhead->th_tran_no)->firstOrFail();
// to this
$pettycashitem = Pettycashitem::where('td_tran_no', $pettycashhead->th_tran_no)->all();
Next, you create an $arr
variable in your controller, but you don't send it to the view. If you need that data, you have to send it to the view:
return view('accounts.pettycash.print')->with('pettycashhead', $pettycashhead)->with('pettycashitem',$pettycashitem)->with('store',$store)->with(['key' => 'td_tran_no'])->with('arr', $arr);
This is not necessary but can be a useful technique for the future. In your controller, you can utilize the relationship to eager load the all of the Pettcashitem
s that belong to the given Pettycashhead
, with your given constraints, see below:
public function print(Pettycashhead $pettycashhead)
{
$pettcashhead= $pettycashhead->with(['pettycashitem' => function ($query) use ($pettycashhead) {
$query->where('td_tran_no', $pettycashhead->th_tran_no);
}])->get();
$store = pettycashitem::all();
$arr['pettycashhead'] = $pettycashhead;
$arr['pettycashitem'] = $pettycashhead->pettycashitem;
return view('accounts.pettycash.print')->with('pettycashhead', $pettycashhead)->with('pettycashitem',$pettycashitem)->with('store',$store)->with(['key' => 'td_tran_no'])->with('arr', $arr);
}
Replied to Showing Slides
As recommended by @joveice, use Laravel's helper loop
variable like this:
<!-- Wrapper for slides -->
<div class="carousel-inner">
@foreach($data3 as $item)
@if ($loop->first)
<div class="item active">
@else
<div class="item">
@endif
<img src="{{ url(Storage::url($item->image)) }}" alt="Los Angeles">
<div class="carousel-caption">
<h3>{{ $item->title }}</h3>
</div>
</div>
@endforeach
</div>
@endforeach
</div>
Replied to Laravel Vue Component Method Not Firing
Make sure that you run npm run watch
so that your changes are picked up on and recompiled. I don't see any other reason why the method is not being called.
Replied to Array Is Not Printing In Blade?
If you are just getting the info for a single Contact
then you can simply remove the foreach
:
<li>{{ $customer->firstName}}</li>
Replied to How To Remove Arrays With Empty Values?
Laravel's Collection methods are really useful for cases. Something like this should work.
$collection = collect($yourArray); //first convert the plain array to a Collection
$filtered = $collection->reject(function ($value, $key) {
return count($value) === 0;
});
Replied to Getimagesize On Url Using Artisan Serve
Interesting. Are there any errors produced, besides a timeout? Also, did you try hardcoding a path, just to be sure that the problem isn't in that area?
Replied to Getimagesize On Url Using Artisan Serve
How big are the image files you are attempting to get the size for? It is noted in the PHP manual that this method is quite slow for large images: https://www.php.net/manual/en/function.getimagesize.php#88793
getimagesize will download the entire image before it checks for the requested information. This is extremely slow on large images that are accessed remotely.
The commentor wrote a small helper function, which may help in this case (the method is included in their comment in the above referenced link)
Awarded Best Reply on Rendering Model Attributes In Markdown
The reason the type hinting made it work was because it told Laravel which class to instantiate so that you then had access to its properties (i.e. url
). If you don't type hint, then Laravel simply provides the Request, without referencing any particular class.
If this worked for you, please mark the response as the best answer so that future users can more easily solve similar issues. Good luck with the project.
Replied to Rendering Model Attributes In Markdown
My guess is that before type hinting, the article
was simply the Request object that was passed to the mailable. I would assume that object had a title
property and that's why it worked. But so long as the KnowledgeBaseArticle
model also has the same title
property, it should work the same.
Also, I just noticed in your build
method, that you are using $this
in the subject but that should not be necessary:
->subject("New DIT Knowledge Base Article - {$article->title}"
Replied to Rendering Model Attributes In Markdown
The reason the type hinting made it work was because it told Laravel which class to instantiate so that you then had access to its properties (i.e. url
). If you don't type hint, then Laravel simply provides the Request, without referencing any particular class.
If this worked for you, please mark the response as the best answer so that future users can more easily solve similar issues. Good luck with the project.
Replied to How To Flat Multidimensional Array Of Objects ?
That makes sense, since flatten
would remove the keys from the id
s and hence, pluck
will not pick up on them. Try just using the pluck
method to see what that returns:
$ids = $collection->pluck('id');
Replied to How To Flat Multidimensional Array Of Objects ?
You should be able to use the collection flatten
and pluck
method to achieve this:
$ids = $collection->flatten()->pluck('id');
Replied to Rendering Model Attributes In Markdown
The mailable looks good to me. Did the typecasting make a difference?
Replied to Rendering Model Attributes In Markdown
Are you properly passing the $article
variable in the mailable like below?
class SendKBNotice extends Mailable
{
use Queueable, SerializesModels;
public $article;
/**
* Create a new message instance.
*
* @param $message
*/
public function __construct(Article $article)
{
$this->article = $article;
}
Replied to URL Appended To Website URL But It's Not Wanted There
I would consider adding a mutator to the url
stored in your DB, so that when you access its contents, they are checked to see if they have an http or https:// and if not, use the mutator to add it to normalize the data. That way, you can easily just use the $links->url
with confidence that it will be a full formed URL. I would default to http:// as opposed to https:// in the mutator.
https://laravel.com/docs/6.x/eloquent-mutators#defining-a-mutator
Replied to Password Protect A Page After Login
This may be of interest to you: https://laravel-news.com/new-password-confirmation-in-laravel-6-2
I'm not 100% sure this meets your use-case, since the user would enter their normal password and not some secondary password. But, if it does, then you can either upgrade your Laravel app to the newest version and get the functionality our out of the box. Or, since Laravel is open source, you can just dig through its repo on GitHub and grab the necessary functions and methods to make this work with your Laravel app.
Replied to Update Empty Checkboxes
Maybe consider radio inputs instead of checkboxes. You may also be able to add a default value to each checkbox. But I'm not 100% sure on that.
Replied to Read Json In Ajax - Undefined
@sinnbeck makes a good point with the response.data
possibility. What does the controller method that sends that data response look like?
Replied to Laravel Policy Is Not Working As Expected
Here are a few ideas that will hopefully help:
//User.php
public function isAdmin(){
return $this->role->name === 'Admin' ; // remove the tertiary here
}
public function role(){
return $this->belongsTo(Role::class);
}
public function isAuthor(){
return $this->role->name === 'Author' ; // remove the tertiary here
}
<?php
namespace App\Policies;
use App\Post;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class PostPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can create posts.
*
* @param \App\User $user
* @return mixed
*/
// still need to pass through the Post model to make the policy work correctly
public function create(User $user, Post $post)
{
if($user->isAuthor() || $user->isAdmin()) {
return true;
}
return false;
}
/**
* Determine whether the user can update the post.
*
* @param \App\User $user
* @param \App\Post $post
* @return mixed
*/
public function update(User $user, Post $post)
{
if($user->id === (int) $post->user_id || $user->isAdmin()) {
return true;
}
return false;
}
/**
* Determine whether the user can delete the post.
*
* @param \App\User $user
* @param \App\Post $post
* @return mixed
*/
public function delete(User $user, Post $post)
{
if($user->id === (int) $post->user_id || $user->isAdmin()) {
return true;
}
return false;
}
}
Replied to Read Json In Ajax - Undefined
Replied to Dynamic Routing With Slugs
There are some helpful options for you in this SO thread.
But, in reality that may add extra confusion to your routes file and it will certainly decrease its readability. So instead of hitting the DB each time to lookup the state name based on the abbreviation, maybe just add a method with a lookup in a helper type file, if that makes sense.