TutanRamon

TutanRamon

Member Since 3 Years Ago

Experience Points
5,360
Total
Experience

4,640 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
18
Lessons
Completed
Best Reply Awards
5
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 2
5,360 XP
Jul
24
2 weeks ago
Activity icon

Replied to Need A Little Help Here Please

Can you post both models?

Activity icon

Replied to Function Argument Is Not Available Inside AJAX Request

Can you also post the Ajax part of your script?

Activity icon

Replied to Compare Two Collections

I think it's not really about comparing the two in this case, it's about checking if a given value is present in the other collection.

Hence, you can use https://laravel.com/docs/7.x/collections#method-contains

Activity icon

Replied to How To Download A Zip File Using Ajax?

Well, what I often do I as follows:

in your controller just simply return the filepath and name in the Ajax succes response and use something like below:

$('#downloadZip').click(function(){
   $.ajax({
      url: 'yourControllerRoute.php',
      type: 'post',
      success: function(response){
         window.location = response;
 }

}); }); });

Jun
10
2 months ago
Activity icon

Replied to Why Vue?

You don't need to use Vue. That's up to you.

Quote: Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don't have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the Vue library. https://laravel.com/docs/7.x/frontend#introduction

Activity icon

Replied to Downloading The Freshly Zipped File

What happens? Do you see blank page, an exception or something else?

Activity icon

Replied to Downloading The Freshly Zipped File

How is this method triggered? Directly or using Ajax?

Activity icon

Awarded Best Reply on Zipping And Downloading Files

You can use PHP's ZipArchive class, see https://www.php.net/manual/en/class.ziparchive.php

There are many tutorials on the web about this class.

EDIT: see example below from https://laraveldaily.com/how-to-create-zip-archive-with-files-and-download-it-in-laravel/

//Archive all files in a folder storage/invoices

$zip_file = 'invoices.zip';
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$path = storage_path('invoices');
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file)
{
	// We're skipping all subfolders
	if (!$file->isDir()) {
		$filePath     = $file->getRealPath();

		// extracting filename with substr/strlen
		$relativePath = 'invoices/' . substr($filePath, strlen($path) + 1);

		$zip->addFile($filePath, $relativePath);
	}
}
$zip->close();
return response()->download($zip_file);

(credits to original author Povilas Korop)

Activity icon

Replied to Zipping And Downloading Files

You can use PHP's ZipArchive class, see https://www.php.net/manual/en/class.ziparchive.php

There are many tutorials on the web about this class.

EDIT: see example below from https://laraveldaily.com/how-to-create-zip-archive-with-files-and-download-it-in-laravel/

//Archive all files in a folder storage/invoices

$zip_file = 'invoices.zip';
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

$path = storage_path('invoices');
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
foreach ($files as $name => $file)
{
	// We're skipping all subfolders
	if (!$file->isDir()) {
		$filePath     = $file->getRealPath();

		// extracting filename with substr/strlen
		$relativePath = 'invoices/' . substr($filePath, strlen($path) + 1);

		$zip->addFile($filePath, $relativePath);
	}
}
$zip->close();
return response()->download($zip_file);

(credits to original author Povilas Korop)

Jun
09
2 months ago
Activity icon

Replied to Inserting Model And Its Relation Together Without Saving Them Individually

Why would you want this? And if you really want it, you should use Database Transactions, see https://laravel.com/docs/7.x/database#database-transactions When, for instance, an error occurs while creating Student, the parent will not be created.

Activity icon

Replied to Store Multiple Checkbox Values

As almost always, there are many approaches to achieve this.

Here's one:

To keep it simple, 2 models: (you can create a seperate model for Price, but in this example I will use 2 models)

Product hasMany Service
Service belongsTo Product

In the Product-table you store the "big car" and the "small car".

In the Service-table you store the ID of the car, and the service (car wash inside etc) and the price for each service.

Now you can easily populate the frontend like this:

$products = Product::with('services')->get();

return view ('index', compact('products') );

In your blade file, you can loop through $products and iterate over the services within a product.

Jun
08
2 months ago
Activity icon

Awarded Best Reply on How To Access Final Model Through Pivot Model?

Ok, figured it out. If somebody else is having the same issues....

In the models where your refer to the pivot model, you need to use the withPivot() function.

So, for example, the Post model now looks like this:

public function sites()
{
	return $this->belongsToMany("App\Site")->withPivot('id')->using('App\PostSite');
}

Thanks to the withPivot('id'), the resulting PostSite model contains its own id. Laravel instantly stopped giving exceptions about null values.

Activity icon

Replied to How To Access Final Model Through Pivot Model?

Ok, figured it out. If somebody else is having the same issues....

In the models where your refer to the pivot model, you need to use the withPivot() function.

So, for example, the Post model now looks like this:

public function sites()
{
	return $this->belongsToMany("App\Site")->withPivot('id')->using('App\PostSite');
}

Thanks to the withPivot('id'), the resulting PostSite model contains its own id. Laravel instantly stopped giving exceptions about null values.

Activity icon

Awarded Best Reply on I Want To Select A Category And Filter The Results Based On That?

I really think you should not just asking this here, but rather look for some more information on this subject. There are really some great tutorials about it. For example, see https://medium.com/@mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8

Activity icon

Replied to I Want To Select A Category And Filter The Results Based On That?

I really think you should not just asking this here, but rather look for some more information on this subject. There are really some great tutorials about it. For example, see https://medium.com/@mykeels/writing-clean-composable-eloquent-filters-edd242c82cc8

Activity icon

Replied to Remove Duplicate Row In Table

The query is rock solid :-) So, that should work.

Do you have an index on your table? You should have an index on 'slug'.

Activity icon

Replied to Unable To Create Or Change A Table Without A Primary Key - Create_oauth_auth_codes_table

Can you try disabling the 'sql_require_primary_key' ? See https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_sql_require_primary_key

Default value is off.

Also, can you check if the 'id' field is indeed the primary key (using phpMyAdmin or other tool)?

Activity icon

Replied to Error Reporting Stopped.

Do you mean that you stopped seeing exceptions in the frontend, or also in the logging files?

Activity icon

Replied to Eloquent WhereDoesntHave()

Besides the whereExists method, there is also an whereNotExists method which you can use to check if the item in table A doesn't exist in table B.

https://laravel.com/docs/7.x/queries#where-exists-clauses (although whereNotExists isn't described there, it is a good starting point to look further).

EDIT: there is also a topic about this on Stackoverflow with some good examples: https://stackoverflow.com/questions/50711923/where-not-exists-en-laravel

Jun
05
2 months ago
Activity icon

Started a new Conversation How To Access Final Model Through Pivot Model?

I have the following four models.

Eloquent models

class Post extends Model
{
	public function sites()
	{
		return $this->belongsToMany("App\Site")->using('App\PostSite');
	}
}

class Site extends Model
{
	public function posts()
	{
		return $this->belongsToMany('App\Post')->using('App\PostSite');
	}
}

class Tag extends Model
{
	public function postSites()
	{
		return $this->belongsToMany('App\PostSite');
	}
}

Pivot model

class PostSite extends Pivot
{
	protected $primaryKey = 'id';
	public $incrementing = true;

	public function post()
	{
		return $this->belongsTo('App\Post');
	}

	public function site()
	{
		return $this->belongsTo('App\Site');
	}

	public function tags()
	{
		return $this->belongsToMany('App\Tag', 'post_site_tag', 'post_site_id', 'tag_id');
	}
}

This setup works fine. I can attach multiple Tag to the PostSite model and I can load them when using the PostSite model as starting point, ie:

$postSites = PostSite::with('tags')->get();

However, in some cases I want the Post model as starting point to get the tags, but I can't figure out how to access the Tags.

$posts = Post::with('sites','sites.tags')->get(); // Exception: Call to undefined relationship [tags] on model [App\Site]

I don't get the error. In the Post model I am telling Laravel to use the App\PostSite model when loading Site. Things like

$posts = Post::with('sites.pivot')->get();
$posts = Post::with('sites','pivot')->get();
    $posts = Post:with('postSite')->get();

don't work either.

Is there some way to get a list of all Posts (with Sites as relation) and see what Tags are attached to the combination (PostSite) of both? How can I use the PostSite model (when using Post as starting point)?

May
26
2 months ago
Activity icon

Replied to BelongsToMany Between Pivot Model And Regular Model

Basicly: see Dossier as as Tag. A Article+Site combination (articleSite) can have zero or more tags.

Activity icon

Replied to BelongsToMany Between Pivot Model And Regular Model

@kkhicher1 That's because it's a many-2-many. I have a table article_site_dossier.

Activity icon

Started a new Conversation BelongsToMany Between Pivot Model And Regular Model

UPDATE: (changed title of topic. Updated title better describes the problem I am having).

I have 4 models (simplified version)

Article
  id
  title

Site
  id
  url
  name

Dossier
  id
  site_id
  name

ArticleSite  (extends pivot)
  id
  article_id
  site_id

I defined the following relations

Article      belongsToMany   Site      using    ArticleSite
Site         belongsToMany   Article   using    ArticleSite
Dossier      belongsToMany   ArticleSite
ArticleSite  belongsToMany   Dossier

The relation between Article and Site is working well. I am experiencing difficulties while saving one or more Dossier to ArticleSite.

I use the sync method to do this, but Laravel keeps returning this error: SQLSTATE[42S22]: Column not found: 1054 Unknown column '' in 'field list' (SQL: insert into article_site_dossier (``, dossier_id) values (?, 5))

I tried defining the column fields in the belongsToMany function, but then the error is about a null value.

The use case of the setup is as follows:

There are multiple Article
There are multiple Site
There are multiple Dossier
One Site has zero or more Dossier
One Article can be shown on multiple Site
One Article (on a Site) can be put in zero or more Dossier

Can anybody tell me what I am doing wrong? Big thanks in advance.

May
21
2 months ago
Activity icon

Started a new Conversation Multi Site News System: Setup Complexity Problem

I am building a multi site news application. So, for instance: while creating a news item (article) I can select multiple sites where I want the item to be shown. Each site has his own "categories" and "dossiers".

Now, I have several models but I repeatedly questioning myself I this is the right approach.

Article Site Category Dossier (= file, not a physical file, but a file as in "part of larger collection of items around a certain subject". Kind of tag.)

An article is attached to 1 or more sites -> "ArticleSite" model

In my Article model I have this pivot relation defined:

public function sites()
{
	return $this->belongsToMany('App\Site')->withTimestamps()->using('App\ArticleSite');
}

The same for my Site model:

public function articles()
{
	return $this->hasMany('App\Article')->withTimestamps()->using('App\ArticleSite');
}

I created a ArticleSite model for the relationship.

class ArticleSite extends Pivot
{
	protected $table = 'article_sites';

	public function dossiers()
	{
		return $this->belongsToMany('App\Dossier', 'article_site_dossiers', 'articlesite_id', 'dossier_id');
	}
}

As you can see, I created a method "dossiers" on the ArticleSite model because a "dossier" is related to article+site. On site A it can be attached to dossier "X" while the same article on site B it can be attached to dossier "Y". Hence, this setup. I am also planning to do this for the categories. Each site holds different categories.

Now, I am having trouble with the dossiers() method. When saving a new article, I can the exception: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'articlesite_id' cannot be null (SQL: insert into article_site_dossiers (articlesite_id, dossier_id) values (?, 1), (?, 5))

This is the part of the ArticleController save method

$articleSite->save();
		
if (isset($request->input('dossiers')[$articleSiteId]))
{
	$articleSite->dossiers()->attach($request->input('dossiers')[$articleSiteId]);
}

(On the frontend I render multiple form sections for each selected site. That's why I use the brackets notation.)

I save the ArticleSite model, so there must be an Id available. I don't get it...

Am I trying to achieve the right setup, or am I trying to get something to work that shouldn't work in the first place? Are there other ways to achieve what I want?

May
20
2 months ago
Activity icon

Replied to How To Search For An Item With Relationships (SOLVED)

Take a look on a recent topic on a similar question. https://laracasts.com/discuss/channels/eloquent/query-with-attributes-from-related-model

@MichalOravec 's answer will give you some clues about how to handle this.

Activity icon

Replied to How To Search For An Item With Relationships (SOLVED)

Can you post your models?

Apr
30
3 months ago
Activity icon

Replied to How To Delete File In Local

But, where is the file located? What is the path on the file on your disc? And how did it came up there?

Apr
29
3 months ago
Activity icon

Awarded Best Reply on Database Relationship

Your users table is missing a foreign key to the profiles table.

Add this to the users table:

$table->bigInteger('profile_id')->unsigned()->nullable();
$table->foreign('profile_id')->references('id')->on('profiles');

EDIT: I think MichalOravec's approach is even better in this case.

Activity icon

Awarded Best Reply on Using Foreach With Old Helper In Laravel Blade

Can you try this:

 @foreach (old('invoices_items') as $i => $invoice_item)
  <input class="input" type="text" name="invoice_items[{{ $i }}][description]" value="{{ $invoice_item[description] }}">
  <input class="input" type="text" name="invoice_items[{{ $i }}][amount]" value="{{ $invoice_item[amount] }}">
  @endforeach

Also, you can skip the @if-check and provide the old helper with an additional empty array:

@php $defaultValues = array(array('description' => '', 'amount' => ''));
@foreach (old('invoices_items', $defaultValues) as $invoice_item)

With the approach, your code will be cleaner.

(not tested it myself, but you get the point)

Activity icon

Replied to Database Relationship

Your users table is missing a foreign key to the profiles table.

Add this to the users table:

$table->bigInteger('profile_id')->unsigned()->nullable();
$table->foreign('profile_id')->references('id')->on('profiles');

EDIT: I think MichalOravec's approach is even better in this case.

Activity icon

Replied to Problem With Populating Database Column With Seeding In Laravel

$user_interests_values is an array, so the exception is kind of valid because he expects a string.

How many interests are there in your interests table?

Because you can also do

'interested_in' =>  rand(1,10)    // generate random id, assuming there are 10 interests with id 1..10

This is a bit dirty, but a quick solution if you just need it for testing purposes.

Activity icon

Replied to Database Relationship

Yes, but show us your migration files for profile and user.

Activity icon

Replied to Database Relationship

If you take a look at the Laravel documentation, you can see the following example:

class User extends Model
{
    /**
     * Get the phone record associated with the user.
    */
    public function phone()
    {
        return $this->hasOne('App\Phone');
    }
}

See https://laravel.com/docs/7.x/eloquent-relationships

So, you are on the right track.

I prefer hasOne('App\Phone') instead of hasOne(Phone::class);

Activity icon

Replied to Using Foreach With Old Helper In Laravel Blade

Can you try this:

 @foreach (old('invoices_items') as $i => $invoice_item)
  <input class="input" type="text" name="invoice_items[{{ $i }}][description]" value="{{ $invoice_item[description] }}">
  <input class="input" type="text" name="invoice_items[{{ $i }}][amount]" value="{{ $invoice_item[amount] }}">
  @endforeach

Also, you can skip the @if-check and provide the old helper with an additional empty array:

@php $defaultValues = array(array('description' => '', 'amount' => ''));
@foreach (old('invoices_items', $defaultValues) as $invoice_item)

With the approach, your code will be cleaner.

(not tested it myself, but you get the point)

Activity icon

Replied to How To Delete File In Local

Well, basically you are now saying Hey Laravel, please delete http://localhost/atc/public/images/workerprofile/Crystalsproof_ofpraveen.png

That's not going to happen. You need to have a reference to the actual file.

use Illuminate\Support\Facades\Storage;

Storage::delete('file.jpg');

See https://laravel.com/docs/7.x/filesystem#deleting-files

Apr
28
3 months ago
Activity icon

Replied to @error Shows Nothing While There Is An Error

Hi Tray2,

Makes no difference. The validation error is shown, but when I switch to @error directive, nothing happens. (I am using to apply corresponding css classes bootstrap.)

Activity icon

Started a new Conversation @error Shows Nothing While There Is An Error

Ok, I have something really weird going on.

I am running the latest Laravel 7 release. Basically, I have a simple controller which validates some user form input.

public function store(Request $request)
{
  $this->validate($request, [
    	'title' => 'required|min:10|max:255',
  ]);

  //rest of the logic
}

When I submit my form (with an incorrect title), the validation trait handles this well. However, my blade file isn't showing the error.

I tried this

@if ($message = Session::get('error'))
  <div class="alert alert-danger alert-dismissable m-t-md">
  {{ $message }}
  </div>
@endif

Nothing shows up. I also tried the @error directive. Nothing happening either.

@error('title')
   <div class="alert alert-danger alert-dismissable m-t-md">
      {{ $message }}
    </div>
@enderror

First I thought the session wasn't flashed correctly. But when I do this:

dd(session()->all()); //in the create method

I got this response:

...
"errors" => Illuminate\Support\ViewErrorBag {#312
#bags: array:1 [
  "default" => Illuminate\Support\MessageBag {#313 
    #messages: array:1 [
      "title" => array:1 [
        0 => "The title must be at least 10 characters."
      ]
    ]
    #format: ":message"
  }
]
}
...

However, when I changed the Blade file to this, it works:

@if($errors->any())
  @foreach($errors->all() as $error)
    <div class="alert alert-danger alert-dismissable m-t-md">
          {{ $error }}
    </div>
  @endforeach
@endif

Does anybody have an idea why @error isn't working?

Activity icon

Replied to I Need To Understand Route And URL

Otherwise, please try a slash before books

Route::resource('/books', 'BooksController')
Activity icon

Replied to Json Url Pass To Laravel Api

I don't understand what you are trying to explain here. Can you explain it with some more information or code?

Activity icon

Replied to Load Default Values From Database To Model

I think you should fix this within the constructor method in your model class.

public function __construct()
{
    $this->something = "default value"; //or fetch from db.
}

One downside I can think of: for every new model, at least one extra db query is fired (to fetch the default values).

Or, if it involves almost all of your models, you should write some generic code that handles this.

Activity icon

Awarded Best Reply on Retain Value Of Radio Button, But Set Default Value

I think you should change

{{ (old('available') == 'unknown') ? 'checked' : ''}}

to

{{ (old('available', 'unknown') == 'unknown') ? 'checked' : ''}}

Now, you pass a default value for "available" if the old value is not set.

Activity icon

Replied to Retain Value Of Radio Button, But Set Default Value

I think you should change

{{ (old('available') == 'unknown') ? 'checked' : ''}}

to

{{ (old('available', 'unknown') == 'unknown') ? 'checked' : ''}}

Now, you pass a default value for "available" if the old value is not set.