Member Since 2 Years Ago

Experience Points

2,660 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
Best Reply Awards
Best Reply
  • start-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-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-token Created with Sketch.


    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.


    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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 6
27,340 XP
1 year ago
Activity icon

Replied to Backend To Frontend View Or Section

ok, so what is the problem you are having trouble with at this point? writing this foreach cycle?

Have you checked this page? https://laravel.com/docs/5.6/blade#loops

If you have a list of items to display, you could also go for DataTables: https://github.com/yajra/laravel-datatables

If you want to style your list of items, you might go for custom styles, and a pagination: https://laravel.com/docs/5.6/pagination

1 year ago
Activity icon

Replied to What Is Best Css Framework?

Well now with V4, Bootstrap has come a long way.

Laravel also comes pre-configured for Bootstrap 3 and 4 - Which you can opt-out of course. But you will need to redesign some defined layouts, such as the Pagination for example, which comes with classes for Bootstrap.

Also, note that many Packages / Plugins, made for Laravel, sometimes work with Bootstrap in mind, such as https://github.com/yajra/laravel-datatables

On the other hand, I hear good things about Bulma. you will just have to work quite a bit using it.

I can also advise Tailwind CSS which I see a lot of Laravel Developers use: https://tailwindcss.com/

Activity icon

Replied to Backend To Frontend View Or Section

Well you could easily just as well create a directory: resources / views / frontend where you can add all your front-end View Files.

You would also create here something like: resources / views / frontend / layouts / master.blade.php which would be your new Front End layout - if you wish to have a different design for the Front End.

Here you would load a different CSS / JS for the new layout. All your new Front End Views would reference this as the Master Layout. All your Controllers would also reference Views from this Folder Group.

It's quite straight-forward. Are you having trouble with something in particular?

Activity icon

Replied to Laravel Iterate Through Unlimited Hierarchy Treeview Non-recursively

I think it also depends on how your Database is Structured. I am guessing, same as me, you are using a single cateogires table, with fields id | name | parent_id where parent_id is referencing self.

This method is more than fine from what I last researched, but you could also go for a Nested Set Model: https://en.wikipedia.org/wiki/Nested_set_model

I found this quite complicated, but luckily there is a package for this: https://github.com/lazychaser/laravel-nestedset


This is also a great research document: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

Activity icon

Replied to Laravel Iterate Through Unlimited Hierarchy Treeview Non-recursively

You shouldn't build your HTML in the controller.

You should build a Blade View, and pass to it the $categories.

Then for each "Parent", call "Self" passing $category->childs => which will be the Parent $category of the "Recursive View". Like this:

<!-- inside category.view -->

@foreach($category->childs as $category)
        @include('category.view', [$category])

As for the recursive method, I think it's fine to use it...

On the Model, I have also used a recursive call like this:

     * get All Children of Parent
     * Parent hasMany children
    public function getChildren() {return $this->hasMany(self::class, 'parent_id');}

     * Department Child Relation
     * child belongs to Parent
    public function parent() {return $this->belongsTo(self::class, 'parent_id');}

     * Recursive Children of ROOT Parent Categories
     * children hasMany getChildren
    public function children() {return $this->getChildren()->with('children');}

Hope this helps

1 year ago
Activity icon

Replied to Relations Issue, How To Make It Correct?

Also I would add, do you need to have 2 separate tables for users and user_infos? if the relation is 1 to 1, you may just simply add the fields of user_infos to the users table, and keep the data in a single table.

Another thing I noticed:

                $table->integer('isFriendly')->length(2)->nullable($value = true);
                $table->integer('isToxic')->length(2)->nullable($value = true);
                $table->integer('isLeader')->length(2)->nullable($value = true);
                $table->integer('isFunny')->length(2)->nullable($value = true);
                $table->integer('isSkilled')->length(2)->nullable($value = true);

These seem to be True/False fields. you may want to save the data as:

1 year ago
Activity icon

Replied to Redirecting Back To Intended Laravel 5.5

yo, sry for late reply.

Just add the Auth Middleware to your Controller for the specific Method

So in your Controller where you are working on, the constructor would be the very first method called. Say you have a HomeController, where you redirect the user to your Home View.

You would have:

  • __constructor() - method
  • index() - method below it

In the constructor, you add the middleware to limit access to the index method.

1 year ago
Activity icon

Replied to Forge Pointing To Wrong Website With Chrome

Strange, it would seem like a problem with your Browser, since it works on other Browsers. Try:

  • Open the website with a Private Session with Chrome.
  • Clear the browser Cache and Cookies. I advise cCleaner: https://www.ccleaner.com/
Activity icon

Replied to In ProviderRepository.php Line 208: Class Not Found

Have you tried:

composer dump-autoload
1 year ago
Activity icon

Replied to Enable/disable Required Policy From The Laravel Boilerplate Forms Dynamically.

In that case, I am guessing you are getting the User Role ID, so in case your User Role ID = 1, for example, then you can write:

// somewhere before validation...
$userRole = 1; // The ID, or if it's a name, then $userRole = 'user';


    return [

        // ...

        'roles' => 'nullable|required_with:extra_field_1,extra_field_2|array',
        'extra_field_1' => 'nullable|required_if:roles,' .$userRole,

        'extra_field_2' => 'nullable|required_if:roles,' .$userRole,


So this should validate the extra_fields just when the "roles" field = $userRole. You just have to make sure you pass the correct value to $userRole, depending on what is passed on your Form (Some use ID as an integer, some use plain text with the role name, some use the ID as a string, so check to make sure)

1 year ago
Activity icon

Replied to Enable/disable Required Policy From The Laravel Boilerplate Forms Dynamically.

What you have right now is different from what you have explained, your field roles is required. I thought you said "Roles" could be set to NULL.

As such, there is no case where "Roles" field can be set to NULL, as you described above. So the extra fields "extra_field_1" and "extra_field_2" will also always be required.

What I told you before based on your previous description would be:


    return [

        // ...

        'roles' => 'nullable|required_with:extra_field_1,extra_field_2|array',
        'extra_field_1' => 'nullable|required_with:roles',

        'extra_field_2' => 'nullable|required_with:roles',


As this stands, the following can happen:

  • "roles", "extra_field_1", "extra_field_2" - can be all left Empty (Null, nothing selected) - Validation will pass
  • "roles", "extra_field_1", "extra_field_2" - must all have a value for the Validation to pass, else the Validation Fails
Activity icon

Replied to Bridging Users, Companies And Transactions


I think that the only case where you should require a PivotTable company_user is if a User can belong to more than 1-company. Otherwise, it wouldn't hurt to keep the relation on the users Table.


Sure, if that works for you. I do not have much experience with hasManyThrough as I have yet to make use of it, but I checked the documentation and it seems correct. You could probably simplify it since you are currently using Laravel Naming Conventions:

public function transactions()
        return $this->hasManyThrough(Transaction::class, User::class);


Again same with the relation between users and companies. If you are certain that the relation is 1:1, then you should keep things in the same Table. I think systems (Servers, Storage and Programs) are now powerful enough to not having to worry about null-assigned fields taking up too much space.

I would think that you owe it to yourself and whoever will take care of your code later to keep things as simple and as easy to manage as possible. But again this would be a personal opinion.

I would only use a PivotTable (or Intermediate Table) for true cases of Many-To-Many Relations, like "Tags / Categories etc..." where I would check if the data has already been used before:

  • If Yes => assign the same data
  • If No => create the new data and assign it / Or Data does not exist exception

Then this data, having the same ID, can be used to fetch all different Models where it has been assigned to. (Like for example, creating a Search for Posts, from certain Categories or Tags / Or Finding all Companies of a User, if more than 1 in your example)

1 year ago
Activity icon

Replied to Enable/disable Required Policy From The Laravel Boilerplate Forms Dynamically.

From what you explained, you have a:

  • role- field
  • extra_field_1
  • extra_field_2 ...

In that case, the best solution would probably be:

  • role=> nullable|required_with:extra_field_1,extra_field_2....
  • extra_field_1 => nullable|required_with:role
  • extra_field_2 => nullable|required_with:role

So, if the "role" field, passed to the Form is NULL, then nothing has been selected, and the validation will not require "extra_field_1" and "extra_field_2".

If a "role" is selected, then the Extra Fields will be required.

If a user tries to play tricks, and fills "extra_field_1" and "extra_field_2", and then empties "role" then it will also throw an exception as they are required with the "role" field.

Activity icon

Replied to Bridging Users, Companies And Transactions

If what you want to achieve is this command:


Then why don't you structure your Database like:

  • companies table => id | ....
  • users table => id | company_id | ...
  • transactions table => id | user_id | ...

Then add relations:

Company Model:

public function users() { return $this->hasMany(User::class); }

User Model:

public function company() { return $this->belongsTo(Company::class); }

public function transactions() { return $this->hasMany(Transaction::class); }

Transaction Model:

public function user() { return $this->belongsTo(User::class); }

Now you can have:

  • Eager Load Relation: $user = App\User::find(1)->with('transactions')->get();
  • Then the results are: $user->transactions;


if 1 Transaction has 1 TransactionDetail, then this table is not needed I think. Simply add the extra fields to the transactions table.

For Transaction Details, you can then have:

  • transaction_details table => id | transaction_id | ... Transaction Model:
public function transactionDetails() { return $this->hasMany(TransactionDetail::class); }

TransactionDetail Model:

public function transaction() { return $this->belongsTo(Transaction::class); }

Then the one you had before becomes:

  • Eager Load Relation: $user = App\User::find(1)->with('transactions.transactionDetails')->get();
  • Then the results are: $user->transactions; To get the details:
@foreach($user->transactions as $transaction)
    {{ $transaction->transactionDetails->id; }}
Activity icon

Replied to Disabling A Table / Class To Migrate Again When Migration:refresh Is Called


In case you do not want to call all the Migrations then you run:

php artisan migrate

Migrate:refresh will call the down() method, and then the up() Method, always.

Usually, when you want to modify a Table (add / remove a field), you create a separate Migration that will take care of that, and then simply run php artisan migrate. The New Migration will have on it's up() method something to make the necessary changes.

Check migrations listed on this Repo for example: https://github.com/Riari/laravel-forum/tree/4.0/migrations

As new changes are made to the code, any modifications to the Tables are added into New Migrations, so it does not break existing code on update.

Activity icon

Replied to Report Designer For Laravel 5.5

Then I advise you check the answers on this Thread: https://laracasts.com/discuss/channels/general-discussion/how-to-get-a-print-view-of-a-page

If you do not want to eventually Print the page, then you should skip those steps, but the DOMPDF Package is a good solid solution to format A4 pages.

Activity icon

Replied to Deploying My Application To Heroku Returns A Service Provider Error

yeah, but you need it locally.

The Provider is taken from the "Vendor" folder. Since DerbugBar is not being installed on Heroku, then the Provider can't be found from the "Vendor" folder, and thus it's giving you the error.

So the solution: You need to install it, and then deactivate it.

How to deactivate it:

After this, DebugBar should work. If you do not want it active on Heroku, change the APP_DEBUG parameter, on your .env file, from true to false.

1 year ago
Activity icon

Replied to Deploying My Application To Heroku Returns A Service Provider Error

Then you have to take the other steps I mentioned, since you have to keep the Provider. Again:

  • when installing Debugbar, by default it is required on dev Environment. Usually Heroku is considered a production environment, so it does not install packages under dev.
  • If you want Debugbar on Heroku, you have to modify your composer.json file, and move the DebugBar Package from require-dev to require.
  • Then push your changes again. Debugbar will now install as a package, and the Service Provider class will be found.

After this, DebugBar should work. If you do not want it active on Heroku, change the APP_DEBUG parameter, on your .env file, from true to false.

Activity icon

Replied to I Have An Issue On Retrieve The Image From The Storage Folder

You can not access the storage folder directly like that. It is 1-level above the public path where your index.php file is located.

You should read this doc: https://laravel.com/docs/5.6/filesystem#configuration

Basically you have to create a symbolic link:

php artisan storage:link

Then you access files using the Storage facade:

  • Storage::put('avatars/1', $fileContents);
  • $contents = Storage::get('file.jpg');
  • $url = Storage::url('file.jpg');
Activity icon

Replied to Deploying My Application To Heroku Returns A Service Provider Error

First of all, on Laravel 5.5+ you do not need to declare a Service Provider, as it is done automatically.

Second, when installing Debugbar, by default it is required on dev Environment. Usually Heroku is considered a production environment, so it does not install packages under dev.

If you want Debugbar on Heroku, you have to modify your composer.json file, and move the DebugBar Package from require-dev to require.

Then push your changes again. Debugbar will now install as a package, and the Service Provider class will be found.

Activity icon

Replied to Report Designer For Laravel 5.5

Like what sort of Report?

The simplest ones would be a table-data? You could have a look at:

Or do you have anything else specific in mind?

1 year ago
Activity icon

Replied to Validation Of Multiple Inputs In Array

I had a similar issue. To solve it, you have to check if the error is for the specific Input Field Name, like so:

<div class="input-product_code {{ $errors->has('product_code.' .$i) ? ' has-error' : '' }}">
    <input id="product_code{{ $i }}" type="text" class="form-control product_code" name="product_code[]" value="@if($getCalendar->count()){{ (old('product_code.' .$i) ? old('product_code.' .$i) : $getCalendar->first()->product_code ) }}@else{{ (old('product_code.' .$i) ? old('product_code.' .$i) : '') }}@endif">

    @if ($errors->has('product_code.' .$i))
        <span class="help-block">
            <strong>{{ $errors->first('product_code.' .$i) }}</strong>


The Value is a little long for me as I am checking for a few cases. You can modify it accordingly.

1 year ago
Activity icon

Replied to Laravel Roles

If the data is really all different, you could do the following:

  • users table: id | role | first_name | last_name | email | password | ... other default fields of Laravel Auth
  • data_members table: id | user_id | ... Other data for Members
  • data_secretaries table: id | user_id | ... Other data for Secretaries

Relations would be:

  • User Model:
public function dataMember() {return $this->belongsTo(DataMember::class);}
public function dataSecretary() {return $this->belongsTo(DataSecretary::class);}
  • DataMember Model:
public function user() {return $this->hasOne(User::class);}
  • DataSecretary Model:
public function user() {return $this->hasOne(User::class);}

to get the data:

if($user->role === 'member') :


Just to be clear, Login Form would remain the same.

I would advise creating a MiddleWare, which would differentiate Users based on their roles. So they would see different pages like, Profile Page, Change your Settings, and so on...

1 year ago
Activity icon

Replied to How I Can Get Data From Multiple Models

Create another Method url:

// Inside Product.php Model
public function url()
    return $this->belongsTo('App\CleanURL', 'clean_url', 'product_id', 'id');

And you can call it:

$categories = Category::with('products.url')->get();

Then you can do the following:

@foreach($category->products as $product)
    {{ $product->url }}
1 year ago
Activity icon

Replied to Convert MySQL Query To Eloquent Or Query Builder

while this is a late reply and you might no longer require it, and my answer is not tested, I think this will work:

$query = Sales::rightJoin(DB::raw('date(sales.created_at) = calendars.datefield'))
    'calendars.datefield as date',
    DB::raw('IFNULL(SUM(sales.sale_total),0) AS total')
    'calendars.datefield between (
      SELECT MIN(DATE(created_at)) FROM sales
    ) AND (SELECT MAX(DATE(created_at)'
1 year ago
Activity icon

Replied to Join Causes Duplicate Results

First of all, do you really need to join the Refunds? If you need to show the data on an "if it exists" basis, then why not just eager-load it?

$processedSales = Sale::with('refunds')
    ->where('sales.user_id', Auth::user()->id)
    ->where('processed', '=', 1)
    ->where('sale_date', '>=', Carbon::now()->subDays($numberOfDays))

If you do need to use the data in such a way that you are required to use join, I would also guess that not all Sales have a Refund. In that case, you'd probably want to use a leftJoin:

$processedSales = Sale::where('sales.user_id', Auth::user()->id)
    ->where('sales.processed', '=', 1)
    ->where('sales.sale_date', '>=', Carbon::now()->subDays($numberOfDays))
    ->leftJoin('refunds', 'sales.user_id', '=', 'refunds.user_id')
    ->select('sales.*', 'refunds.status')
    ->orderBy('refunds.status', request('direction'))

More on different types of Join Here

Activity icon

Replied to How To Improve User's Experience?

On the latest Firefox, mobile view, you get a Javascript Error when trying to open the menu-burger, and the menu does not open at all.

And the SVG-images are overlapping with the content on smaller devices.

You should use the browser's dev-tools to check the responsiveness of every page as you scale the width of the screen from desktop-size to mobile-size.

1 year ago
Activity icon

Replied to I Am Unable To Install Laravel On My Machine

I do not know if you have solved this yet.

  • Try to Uninstall Virtualbox and Vagrant.
  • After that, go to your User Folder: C:\Users\your_user
  • Manually Delete: .vagrant.d, .VirtualBox,VirtualBox VMs
  • Run a clean-up with cCleaner: https://www.piriform.com/ccleaner/download
    • Run a Cleanup
    • Clean the Registry as well
  • Reinstall Virtualbox first
  • Reinstall Vagrant
  • Try to download the laravel box again vagrant box add laravel/homestead (Again Command Line in Administrator Model)

Also note this from the Documentation:

If you are using Windows, you may need to enable hardware virtualization (VT-x). It can usually be enabled via your BIOS. If you are using Hyper-V on a UEFI system you may additionally need to disable Hyper-V in order to access VT-x.

1 year ago
Activity icon

Replied to Redirecting Back To Intended Laravel 5.5

Just add the Auth Middleware to your Controller for the specific Method:

     * Create a new controller instance.
     * @return void
    public function __construct()
        // Only Authenticated Users can access Method 1 and 2
        $this->middleware('auth', ['only' => [
            'specificMethod_1', 'specificMethod_2'

Or to all Except a Specific Method:

     * Create a new controller instance.
     * @return void
    public function __construct()
        // Authenticated Users can access any method except specificMethod
        $this->middleware('auth', ['except' => [

Laravel takes care of it out-of-the-box.

If the user is required to be authenticated, they will, and then they will get redirected to where they were previously.

Activity icon

Replied to I Am Unable To Install Laravel On My Machine

Are you on Windows 10?

First try to run the Command-Line as Administrator.

If that does not work, I see that Vagrant 2.0.1 is reported Here to have broken something on Windows. So try to uninstall Vagrant and reinstall v.2.0.0.

Although I have Vagrant 2.0.1 and everything seems to be working fine for me.

Activity icon


You should avoid any queries inside your View.

These should be done in the Controller and/or Model Level. From your View you should simply pass a request to the Controller, and it would give you a response back into your View.

1 year ago
Activity icon

Replied to -> OrWhereHas Failed Fetch Data From Multiple Tables

You do not need to do that. Instead of:

->orWhereHas('writter', function ($query) use ($keyword) {
            $query->where('nama_penulis', 'like', '%'.$keyword.'%');

You do:

->orWhereHas('writter', function ($query) use ($keyword) {
            $query->whereRaw('LOWER(nama_penulis) like ?', "%$keyword%"); // Only this needs to be changed
Activity icon

Replied to Handling Large Dataset (1000+) In VueJS

Adding to the response from @Spillmester there is a nice package for Laravel to ease the implementation of DataTables: yajra/laravel-datatables

Search and pagination are handled server-side through AJAX.

Bootstrap 3 theme included.

This is not VUEjs, but if all you want is to show a table with pagination and searchable, I think as well that using DataTables would be your best solution.

Activity icon

Replied to -> OrWhereHas Failed Fetch Data From Multiple Tables

You're welcome, I am glad that worked out.

As for ilike, I thought it was not recognized on MySQL from what I have read. My solution with whereRaw was meant to add support so your application works both locally on MySQL and Live on PostgreSQL.

1 year ago
Activity icon

Replied to -> OrWhereHas Failed Fetch Data From Multiple Tables

I believe the issue might be that Postgres Does not work well with like, as for Postgres like is case sensitive while for MySQL is by default Case Insensitive. Postgres has ilike for case insensitive but that does not work with mySQL...

Try using whereRaw instead. For Example:

$query = Book::whereRaw('LOWER(judul) like ?', "%$keyword%")
    ->orWhereRaw('LOWER(label) like ?', "%$keyword%")

This has worked for me on Heroku with no problems.

Also, I advise:

  • Testing the code 1 by 1, as you add more conditions to see if it fails anywhere else
  • Install and enable debugbar so you can see the query that is being executed on Heroku-side
  • Install HeidiSQL which has a PostgreSQL Connection Option. I have found it useful to get the Query executed from DebugBar, and execute it on HeidiSQL to get more information on where the code was failing.


Notice that the Keyword also needs to be lowercase. So somewhere you need to:

$keyword = strtolower(trim($keyword));
1 year ago
Activity icon

Replied to User (client) Accounts & Sub Accounts?

adding to the answer from @andonovn

You can modify the default users table, created by the laravel php artisan make:auth by adding a parent_id field (or users_id if you want to follow default Laravel naming conventions), so you will end up with (at it's simplest):

  • users table fields => | id | parent_id | name | password | created_at | updated_at |

From here, you connect users table, with itself, thus creating a parent-child relation.

When a Client, from their profile-page creates new Sub Accounts, it's ID is added to the parent_id field.

You will also require something to differentiate Default Clients from SubAccount Clients. You can:

  • Add a database-level logic, by adding a field main_account => which would be, for example, true or false. You can get a listing of Main Accounts ->where('main_account', true)->get();
  • Or a server-level logic, where you check the client if they have any value in their parent_id field.
    • If parent_id = null, this is a Main Account ->whereNull('parent_id')->get();
    • If parent_id !=null, this is a SubAccount

And you can show different Views based on this logic, with different functions (SubAccounts can not create other SubAccounts for themselves)

1 year ago
Activity icon

Replied to Should I Repeat Separate Or Reuse A Nested Controller That Has Overlapping Purpose?

Could you give an example of what you actually intend to do?

If I am understanding you correctly, you intend to have 4 tables?

  • videos / Video Model / VideosController
  • skills / Skill Model / SkillsController
  • strengths / Strength Model / StrengthsController
  • flexibilities / Flexibility Model / FlexibilitiesController

And you would end up with:

  • videos table => | id | skill_id | strength_id | flexibility_id | name |
  • skills table => | id | name | other_data |...
  • strengths table => | id | name | other_data |...
  • flexibilities table => | id | name | other_data |...

Video Model would have belongsTo relation to all other tables, while all other tables would have hasMany relation to Videos:

// Video Model
public function skill() { return $this->belongsTo(Skill::class); }
public function strength() { return $this->belongsTo(Strength::class); }
public function flexibility() { return $this->belongsTo(Flexibility::class); }

// Skill Model
public function videos() { return $this->hasMany(Video::class); }

// Strength Model
public function videos() { return $this->hasMany(Video::class); }

// Flexibility Model
public function videos() { return $this->hasMany(Video::class); }

If that is the case, what kind of data would these tables store exactly? I feel you might be doing too much if there are not really that much data being stored on each separate table.

Having many tables instead of 1 isn't really making things simpler. You should focus on having simple-code, but not necessarily simpler storage for that code. The database won't mind if you have 3-4 more Columns in the videos table.

If a category could have different set of data, as you said, you could store them in the same table, and end up with null-values, but depending on the type of data, and how much data it is, I do not think it should take much more space:

  • categories table => | id | name | data_strength_1 | data_strength_2 | data_skill_1 | data_flexibility_1 | ... When you select the data, you could specify them in the select:
$strengthVideos = Video::where('category_id', '=', '1' /* strength */)->select('id', 'name', 'data_strength_1', 'data_strength_2')->get();

If 1 video can have more than 1-category, on the other hand, you can have a pivot table:

  • videos table => | id | name |
  • categories table => | id | name |
  • category_video table => | category_id | video_id |

So now you can match 1-video with many categories. And 1-category with Many Videos. This is a Many-To-Many Relationship.

Activity icon

Replied to Suggestions On A How To Carry Out A Particular Task.

OK so from the top of my head, here is what I am thinking:

  • For the Bus Seats you can use Select2
  • I feel some form of seat-number confirmation / assignment should be available for print to the user in some way. (An e-mail with the order: bus plate, departure_time, seat_number)
  • An e-mail confirmation of the reservation should be sent to the user. In case of a conflict between 2-users trying to reserve the same seat, they should get a notification to take another reservation, or as I said above, maybe assign an empty one in case there aren't many left free, so they do not get left without a seat entirely because they could not come to the system again to change their reservation

Table structure could be:

  • buses => | id | plate?number |
  • seats => | id | bus_id | => I think this will facilitate things. For example, showing a list of seats from a specific bus. Or if in the future, you might get different bus-sizes, with different seat count
  • events => | id | name | bus_id ? if Only 1 bus per event, else place in reservations table |
  • reservations => | id | event_id | bus_id =>if more than 1 buss per event | client_id => default(null) | seat_id | reserved => default(false) |

So here is my thinking.

  • When you create an event, you select some Buses for it.
  • On Event Creation, the reservations table will populate with 1-row for each Bus Seat (50 seats / bus, 2 buses selected, 100 rows), with the reserved field defaulting to false and client_id defaulting to null.
  • When client wants to join an event, a list of Bus-Seats will be available, where reserved = false.
  • When user selects a Seat and Submits the form, the Appropriate reservations table will update with the user's ID, and reserved = true.
  • From here you can see which seats are still available. You can get data for the User: Event, Bus, Seat, etc.

I might have missed something but I think the core is here.

Activity icon

Replied to Multirelations With 3 Tables

I am not that great with programming myself. As I stated above, this is my "Personal Opinion". You can follow your own goals or wait for someone else to give their opinion which might support yours.

Games and Platforms are fine to have a relation. Did you read my post above?


Your users table should have:

  • id => primary Key

Your games table should have:

  • id => Primary Key
  • user_id => Foreign Key, related to users table // If you are saving a list of games for a User, otherwise, you can remove this as well.

Your platforms table should have:

  • id => Primary Key

You should have a Pivot Table game_platform for the relation between games and platforms, which should have these fields:

  • game_id => Foreign Key to games Table
  • platform_id => Foreign Key to platforms Table

If you want games under PC Platform then you will end up with something like:

// In your Controller
$platform = Platform::where('name', '=', 'PC')->with('games')->get();

// In your View
    @foreach($platform->games as $game)
        <li>{{ $game->name }}</li>

If you want users, who own a game, under PC Platform:

// Your Controller
$platform = Platform::where('name', '=', 'PC')->with('games.users')->get();

// Your View
    <!-- list of games -->
    @foreach($platform->games as $game)
        <li>{{ $game->name }}</li>
        <!-- For Each Game, list of users who own it -->
            @foreach($game->users as $user)
                <li>{{ $user->name }}

And there you have it.

If you wish you might have a many-to-many relation between games and users as well, so there is no redundancy in the games field. Again depends on your project and what you wish to achieve.

So you can have: users <=> game_user <=> games <=> game_platform <=> platforms

So you will have to change these table structures:

  • users table => | id | name |
  • games table => | id | name |
  • game_user table => | game_id | user_id |

The Queries will still work the same after you have declared the Relations on the Models.


What do you plan to do in this case:

  • You add a New Game
  • You add Platforms for the game => will populate your games_users_platforms => what user_id will you add in this example? No User owns this new game yet, it was just added to the system.
Activity icon

Replied to Multirelations With 3 Tables

Well first of all, I must say it is my personal opinion that this relation makes no sense. There is no reason the users table is connected to the platforms table directly. It should connect only through the games table, as I have described above.

Next, as far as I know, Laravel does not support this. So you are probably going to have to write every method yourself to Keep these data in Synchronization.

Still, if you want to continue with this method, I think this might work out for your case. But again this would simply simulate three 2-way pivot tables: game_user, platform_user and game_platform. These are all ManyToMany Relations.

A Many To Many Relation is declared like this:

return $this->belongsToMany('App\Model', 'foreign_key', 'local_key', 'table_name');

So for your case, the User Model is like this:

public function games() {
    return $this->belongsToMany(Games::class, 'user_id', 'id', 'users_games_platforms');

public function platforms() {
    return $this->belongsToMany(Platform::class, 'user_id', 'id', 'users_games_platforms');

The Game Model:

public function users() {
    return $this->belongsToMany(User::class, 'game_id', 'id', 'users_games_platforms');

public function platforms() {
    return $this->belongsToMany(Platform::class, 'game_id', 'id', 'users_games_platforms');

The Platform Model:

public function users() {
    return $this->belongsToMany(User::class, 'platform_id', 'id', 'users_games_platforms');

public function games() {
    return $this->belongsToMany(Game::class, 'platform_id', 'id', 'users_games_platforms');

So now, if the above works, you should be able to do the following:

  • $user = User::find($id)->with('platforms'); to get the Platforms of a User
  • $user = User::find($id)->with('games'); to get the Games of a User
  • $game = Game::find($id)->with('users'); to get the Users of a Game
  • $platform = Platform::find($id)->with('users'); to get the Users of a Platform

But again I seriously advise against going though with this method and follow the one I posted previously.

Activity icon

Replied to If Exist Take Id If Not Create New Client

You can do this:

  • Use Select2 to build a Search-Form. You can check This Tutorial.
  • While you type, the Database will be searched for a Client, which you can select and Submit, so you can for example, be taken to the Client's Page
  • If nothing is found, Select2 has an option to select what you have typed anyhow

You can then create other Routes and Controller, which will try to find the Client-ID (id would be same as name for the case where Client is not found but you selected it anyway). So the Controller would either:

  • Redirect to Client Page, if Client is found
  • Redirect to Client Creation Form, if Client is not Found

In case you are dealing with a new Client, you would redirect to a New Route, where you would create this new Client, and the Client Name could be auto-filled. You would then fill the other data, and finalize the creation of the Client.

Activity icon

Replied to Should I Repeat Separate Or Reuse A Nested Controller That Has Overlapping Purpose?

First thing that comes to mind, is this necessary?

Wouldn't it be better to have:

  • VideosController => To take care of everything
  • Have a category field in your videos table, which will save data like "skills / flexibility / strength".

So when you need to access "Strength Videos" you can do: $videos = Video::where('category', '=', 'Strength')->get();

Otherwise, you are right. You should have a VideosController, and all other controllers would extend this base-controller. Keep everything here, like validation method, store method, edit method, and so on. Keep it DRY (Don't Repeat Yourself)

Activity icon

Replied to Suggestions On A How To Carry Out A Particular Task.

I would have some questions:

  • Is it necessary? Or are you trying to make it fancy? Do you have a logic behind this specification?
  • Is this a Bus Service that goes around Town? with regular stops?
  • Or is it a Bus Reservation like a Taxi, for events with a specific destination, like a camping trip.
  • Do you have any method in mind to deal with users trying to get the same seat at the same time? Like an e-mail after the fact that the seat was requested a little-bit sooner by someone else?
  • Would they go back to register again or would a random empty-seat be assigned to this user who lost their reservation?
  • Would you print a reservation coupon of some kind for these users? Or do the bus-seats have a digital output that would print the person's name or Reservation Number?
Activity icon

Replied to Making A Laravel 5.4 Query On A JSON Field Containing A JSON Array

Can you modify how this is stored? So that you can remove the [ ] ?

Activity icon

Replied to How Can I Display Data Uniformly Insert (include Symbol,space,enter..)

So you are writing this on a textarea HTML-tag? and you wish it to keep it's format?

In that case, you need to be aware first that Laravel strips some special characters when you echo something in blade using this method:

{{ $yourData }}

To stop Laravel from stripping the special characters, you need to do this:

{!! $yourData !!}

Notice: This is not safe.

Some of the special characters that Laravel removes also includes things that could be used to hack your application. To avoid that, you need to strip these bad-characters Before Saving them on your database.

For that you need to Sanitize the Input before saving it. I found these packages that you might consider:

Activity icon

Replied to Database Design For Ecommerce Website Example

Well this all depends on your specifications.

If you are working on a project from a client, normally first thing to do would be to take the business specifications from that client and start building your Database Relations from there.

You might also look into Spark, if it's a big project, to get you started on a solid foundation. https://spark.laravel.com/

If you are doing something for yourself, the best advise I would give you would be to start small, just the bare minimum. for example:

  • categories table. Maybe do not build a parent-child relation as a start.
  • products table. Start with a name and a price. connect it to the payment system you want to build first, and then start adding to the table things like discount, tax, vat, manufacturer, magazine, and so on...

You should check some of the e-commerce solutions for Laravel, so you can get an idea of what the others are doing:

You can check this tutorial that builds an e-commerce application from scratch, integrated with PayPal: https://www.codementor.io/pknerd/posts

Hope these help

1 year ago
Activity icon

Replied to How To Show Project Name In Limited Characters In Laravel?

In your view, do this:

{{ substr($proj->project_name, 0, 10) }}

More available functions Here

Activity icon

Replied to How To Build A Worklog Table By Month?

It's gonna be a bit hard for me, without making tests, to provide a working answer right away, but I'll try my best.

First of all, I think you should make the transformations in your View in this case. Some of the logic in the Controller and Model. And just query the data from the Database.

projects Table

| fields |
| ------ |
| id |
| name |
| created_at |
| updated_at |

worklogs Table

| fields |
| ------ |
| id |
| project_id |
| log |
| created_at |
| updated_at |


Based on the response here, I think this should work:

$year = $request->year;

$workLogs = Project::leftJoin('worklogs', 'projects.id', '=', 'worklongs.project_id')
    ->whereRaw("(YEAR(worklongs.created_at) =  ?)", [$year])
        'projects.id as id',
        'projects.name as name',
        DB::raw('MONTHNAME(worklogs.created_at) as month'),
        DB::raw('COUNT(DISTINCT worklogs.id) as month_total')
    )->orderBy('worklogs.id', 'month')
    ->orderBy(DB::raw('FIELD(MONTH,"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")'))
    ->groupBy('worklogs.id', 'month')->get();

This query will need to be tweaked a little so it shows something when the month_count is 0. This should get data like below:

| id | name | month | month_total |
| ------ | ------ | ------ | ------ |
| 1 | project_1 | January | 5 |
| 1 | project_1 | February | 10 |
| 2 | project_2 | January | 15 |
| 3 | project_3 | December | 4 |
Next, Group them by ID to separate Projects
$projects = $workLogs->groupBy('id');

This will give a collection, groupedBy Projects.


<table class="table table-striped table-responsive">
    <!-- Treat each $projects Collection as 1-Project -->
        @foreach($projects as $project)
                <th scope="row">{{ $project->first()->name }}</th>
                <!-- Treat the data inside each project as 1-separate Worklog -->
                <!-- Assuming the Query is fixed above - Each month should be iterated -->
                <?php $totalCount = 0; ?>
                @foreach($project->all() as $worklog)
                    <td>{{ $worklog->month_total }}</td>
                    <?php $totalCount += $worklog->month_total; ?>
                <td>{{ $totalCount }}</td>

Edit: Can't find anything to set a default month_total Count to be 0, if there are no worklogs at all for a given month.

Only solution would be to create a separate Table months, which would store all 12-month names. Then add a join to modify the query. Or join a subQuery as suggested Here

Activity icon

Replied to How To Build A Worklog Table By Month?

How do you differentiate years here?

Are worklogs from January 2016 and worklogs from January 2017 both summed-up in the same Table-cell?