fdusautoir

fdusautoir

Member Since 4 Years Ago

Experience Points 29,920
Experience
Level
Lessons Completed 229
Lessons
Completed
Best Reply Awards 2
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

07 Oct
2 months ago

fdusautoir left a reply on Jquery To Vue

Any help ? :)

06 Oct
2 months ago

fdusautoir started a new conversation Jquery To Vue

Hi everybody.

I followed the vue series and I didn’t find an answer to the following thing :

I have a project with some jquery code on multiple pages. What’s the best practise to begin a migration to vue ? Do I have to create an instance to Vue in my app.js and create a component for a page ?

Also, Jeffrey seems to have created an autoload for components. Is there a video about this ? I didn’t see it.

Thanks for you answers.

30 Sep
2 months ago

fdusautoir started a new conversation Scopes - Good Practise

Hello,

I use scopes for add constraints to my queries but also to achieve that kind of thing :


public function scopeNotify($query, $message)
    {
        return $this->notifications()->create([
            'text' => $message
        ]);
    }

which allows me to in Controllers or Events to use :


$user->notify('hello world');

I wonder if it is a good practice or if I can achieve that in a more convenient way ?

Thanks for your answers.

fdusautoir left a reply on Casts In Model

Sorry, that's working. I had forgotten to except the administrative attribute too ...

fdusautoir started a new conversation Casts In Model

Hi there,

In my model, I have a method call updateProfile. This method is called from several Controllers.

 public function updateProfile(Request $request)
    {
        $this->update($request->except('commercial'));
    }

In the request, I have two attributes which are normally casts as object. I have an error because it doesn't convert my two array with json_encode.

I think because I'm in the model, the casts method is not apply to my two attributes.

Any pretty solutions about that ? :)

Thanks.

28 Sep
2 months ago

fdusautoir started a new conversation Auth:: Or Auth()

Hi there,

I wonder if there is a significal difference to use auth() instead of using the facade Auth within my controllers ?

Thanks for your answer.

19 Sep
2 months ago

fdusautoir started a new conversation Group By And Paginate

Hi Everybody,

I have an issue using group by with paginate.

This works well :

$headlines = ProgramHeadline::all()->groupBy('month');

But when I try :

$headlines = ProgramHeadline::groupBy('month')->paginate(6);

I have this error :

SQLSTATE[42000]: Syntax error or access violation: 1055 'auan.program_headlines.id' isn't in GROUP BY (SQL: select * from `program_headlines` group by `month` limit 6 offset 0)

So far, if I test this request in Sequel Pro : That's working ! I searched about this issue and I've turn off the strict mode in config/database.php, that's working but I consider that's not a good solution as Taylor said in a comment.

So, what's going wrong here ?

Thanks for your help :)

18 Sep
2 months ago

fdusautoir left a reply on Min Or Max On Pivot Field

@staudenmeir Thanks you're right. I was sure to have test it, nevermind ! :)

fdusautoir started a new conversation Min Or Max On Pivot Field

Hello Everybody,

I would like to apply the min or max eloquent aggregate method on pivot field but I don't succeed in, I tried pivot_price_minor pivot->price_min but that not worked.

Have you an idea ?

For the moment I use a foreach to achieve that and that works :


public function getDwellingsInfosAttribute()
    {
        $dwellings = $this->dwellings()->get();
        $prices_min = [];
        $prices_max = [];

        foreach($dwellings as $dwelling)
        {
            $prices_min[] = $dwelling->pivot->price_min;
            $prices_max[] = $dwelling->pivot->price_max;
        }

        $prices_min = collect($prices_min);
        $prices_max = collect($prices_max);

        return (object) [
            'type_from' => $dwellings->min('name'),
            'type_to' => $dwellings->max('name'),
            'price_min' => $prices_min->min(),
            'price_max' => $prices_max->max(),
        ];
    }

But I would prefer something like that :


public function getDwellingsInfosAttribute()
    {
        $dwellings = $this->dwellings()->get();

        return (object) [
            'type_from' => $dwellings->min('name'),
            'type_to' => $dwellings->max('name'),
            'price_min' => $dwellings->min('pivot_price_min'),
            'price_max' => $prices_max->max('pivot_price_max'),
        ];
    }

Any ideas ? :)

Thanks for your help.

28 Aug
3 months ago

fdusautoir left a reply on Route Resource Names

Any ideas ?

fdusautoir started a new conversation Route Resource Names

Hi there,

This is my actual route resource :

Route::resource('mes-alertes', 'AlertsController')->names([
            'index' => 'alerts.index',
            'create' => 'alerts.create',
            'store' => 'alerts.store',
            'edit' => 'alerts.edit',
            'update' => 'alerts.update',
            'destroy' => 'alerts.destroy',
        ])->except(['show']);

Instead of this and to prevent to name each action, I tried to achieve this like this :

Route::resource('mes-alertes', 'AlertsController', ['as' => 'alerts'])
        ->except(['show']);

But that's not working as excepted :

account.alerts.mes-alertes.index
account.alerts.mes-alertes.store
account.alerts.mes-alertes.create
account.alerts.mes-alertes.update
account.alerts.mes-alertes.destroy
account.alerts.mes-alertes.edit

Any ideas ? :)

20 Aug
3 months ago

fdusautoir left a reply on Laravel And Security With .git

Thanks both for your answers. Obviously, I didn't think about the public folder.

fdusautoir started a new conversation Laravel And Security With .git

Hi everyone,

I'm curious about something.

As you probably know, there's a famous hack which consists in going to ** yoursite.com/.git/logs/HEAD ** and get the deposit's url to clone website and collect informations.

With Laravel, access to the .git directory displays a 404 errors. Where does it handle in the core ?

14 Mar
9 months ago

fdusautoir left a reply on Concatenation In Require

Any help ? :/

13 Mar
9 months ago

fdusautoir started a new conversation Concatenation In Require

Hi Everybody,

I have a very strange problem.

All this code below is working fine :

        payload.modules.forEach(function(mod) {

            var modules_path = '../../modules/';

            // Routes
            router.addRoutes(require('../../modules/'+mod.module_id+'/routes.js'));
            // Store
            store.registerModule(['modules', mod.module_id], require('../../modules/'+mod.module_id+'/store.js').default);

        });

But when I use the modules_path variable into my require like this :

        payload.modules.forEach(function(mod) {

            var modules_path = '../../modules/';

            // Routes
            router.addRoutes(require(modules_path+mod.module_id+'/routes.js'));
            // Store
            store.registerModule(['modules', mod.module_id], require('../../modules/'+mod.module_id+'/store.js').default);

        });

What can explains that ? That seems to be the same for me.

Thanks for your help :)

fdusautoir left a reply on Vue And Alias

That's okay, in my webpack.mix.js file I've added this and that's works fine :

let src_path = 'resources/assets/js/';

mix.webpackConfig({
  resolve: {
    alias: {
      '@src': path.resolve(__dirname, src_path),
      '@store': path.resolve(__dirname, src_path + 'store/'),
      '@views': path.resolve(__dirname, src_path + 'views/'),
      '@components': path.resolve(__dirname, src_path + 'components/'),
      '@modules': path.resolve(__dirname, src_path + '/modules/'),
    }
  }
});

``
11 Mar
9 months ago

fdusautoir left a reply on Vue And Alias

Mmm I don't think that is a clean way to achieve that. I'm thinking about webpack.mix and aliases but I don't understand how it works. @JeffreyWay any videos or help about this ?

09 Mar
9 months ago

fdusautoir left a reply on Vue And Alias

@ejdelmonico @Cronix For sure that’s not answer to my question ;). Any help ?

fdusautoir started a new conversation Vue And Alias

Hi Everybody.

How can I have alias in my vue files ? to prevent to use relative path everywhere ... That is not very convenient if I change the app structure in a future.

for example in my ./store/index.js I have in a function :

router.addRoutes([
            {
                path: '/clients',
                component: require('../../views/Clients.vue')
            },
        ]);
                

The best would be (as in Laravel) :

router.addRoutes([
            {
                path: '/clients',
                component: require(views_path('/Clients.vue'))
            },
        ]);

What is the best way to achieve that ?

Thanks for your help ! :)

17 Apr
1 year ago

fdusautoir left a reply on Request Fields In Model

@leber, for sure but in this case, I don't need to check datas, in that case, I would pass the formRequest variable to my function.

fdusautoir left a reply on Request Fields In Model

Thanks both for you answer, in fact, I just began phpunit and wonder if this way to proceed will be valid for testing in a simple way.

fdusautoir started a new conversation Request Fields In Model

Hello Everybody,

I wonder if I took the right way in my application. For example, in my FooController I have :


public function submit(Foo $foo)
{
    $foo->submit();
    return back();
}


public function publish(Foo $foo)
{
    $foo->publish();
    return back();
}

And in my Foo model :


private function updateFields($status)
    {
        $this->update([
            'body'        => request('body'),
            'body_draft'  => request('body'),
            'status'     => $status,
            'difficulty' => request('difficulty') ?: $this->difficulty,
            'comment'    => request('comment') ?: $this->comment,
        ]);
    }
    
    public function submit()
    {
        $this->updateFields('submit');
        $this->archive('submit');
    }
    
    public function publish()
    {
        $this->updateFields('publish');
        $this->archive('publish');
    }


Is it a good way to proceed or it not recommend to use request in model and why ?

Thanks for your help ! :)

30 Mar
1 year ago

fdusautoir left a reply on Login Redirect When Errors

Thanks for your help. In fact, that's a part of the answer. I solved the problem in two steps.

First, I override the protected function login() with a FormRequest to be able to override the protected $redirectRoute variable.

Then to finish, I override the sendFailedLoginResponse() .

Now, if I validate form with missings data in the header OR if I failed validation, it redirects to the login form as expected. :)

29 Mar
1 year ago

fdusautoir left a reply on Login Redirect When Errors

Thanks for your answer. I already try this with a return die()but nothing appends, it still redirect back with errors

fdusautoir started a new conversation Login Redirect When Errors

Hi There !

I have a tiny login form in my header page with this code :


{!! Form::open(['route' => 'login']) !!}
    <input type="text" name="email">
    <input type="password" name="password"">
    <button type="submit">Login</button>
</form>
{!! Form::close() !!}
                                        

When I click the login button, it redirects to the same page with errors validations. All is OK at this point but I don't want this redirect()->back()native redirection which is not really clear for the user (the login form is in a submenu in the header). How to redirect to the 'real' login page with errors which is accessible at the php route('login.form') ?

Thanks for your help ! :)

04 Mar
1 year ago

fdusautoir left a reply on Multi Domains

@mikefolsom You're right for the canonical. That was not a good example here. I just updated my post with a new example to explain that I want to achieve.

fdusautoir started a new conversation Multi Domains

Hi there.

I have one site with multiple domains. For example :

  • example.fr
  • example.be
  • example.lu

Those have the same language and when I visit a page I just want to update the href on the canonical meta with the extension that is used to access the page. For example, if i'm on example.be/my-page . I want to have :

<meta name="canonical" href="example.be/mypage">

For example.lu/my-page :

<meta name="canonical" href="example.lu/mypage">

How to achieve that in a proper way ? In fact, it would be great if it would exists a $request->getDomainExtension() function .

Thanks for you help.

27 Feb
1 year ago

fdusautoir started a new conversation Optimisation Avg

Hello !

I have a table with products and another one with product_ratings which store all ratings by user.

What is the best way to optimize queries to get the average rating on the product ?

Use eager loading on the product model with ratings relation or to add a rating column to the product table and update it only when a user rate the product ?

A simple question but I wonder if it could be increase performance with a lot of traffic.

15 Feb
1 year ago

fdusautoir left a reply on Markdown And Inline Attachments

Someone to help me please ?

fdusautoir started a new conversation Markdown And Inline Attachments

Hello Everybody !

I try to embed inline images in my mail template but I have an error :

Undefined variable: message (View: /Users/francois.dusautoir/Code/lvdp/resources/views/emails/request/received.blade.php)

received.blade.php

    
@foreach($request->files as $file)
![image]({{$message->embed($file->path)}})
@endforeach

** RequestReceived.php **

namespace App\Mail;

use App\Request;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class RequestReceived extends Mailable
{
    use Queueable, SerializesModels;

    public $request;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->subject('Foo - Bar')
            ->markdown('emails.request.received');
    }

Relative to the documentation :

use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually.

Any help here ? :/

14 Feb
1 year ago

fdusautoir left a reply on Dropzone And Laravel

Not a mistake but my mistake. I tried to return response like json with instance of UploadedFile, that has no public properties and so I could'n see it in the browser console.

fdusautoir left a reply on PHPStorm Automatic Reformat

It is checked. That's very strange ...

fdusautoir left a reply on Dropzone And Laravel

The console image :

console

fdusautoir started a new conversation Dropzone And Laravel

Hi everybody !

I want to implement dropzone into my form. When I click the submit button of the general form, it launch the dropzone queue, that's okay. All that I want for the moment is getting the filename from my Controller after sending it but I have an empty array for the file.

This is what i did :

In my contact.blade.php :


<form id="contact-form" class="form" action="{{action('[email protected]')}}" method="POST">

    ...
    // Some input fields 
    ...

    <!------ Fields  ------>
                <div class="form-group">
                    {!! Form::label('', 'Vous avez des croquis ?') !!}
                    <div id="files" class="dropzone" data-url="{{route('contact-form-file')}}"></div>
                </div>


</form>

In my contact.js :


$("#files").dropzone({
        url: $('#files').attr('data-url'),
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 3,
        maxFiles: 3,
        paramName: 'file',

        init: function() {
            var myDropzone = this;

            $('#contact-form').submit(function(e) {
                if(complete) {
                    return true;
                }

                var $button = $(this).find('button');
                $button.addClass('proceed');
                myDropzone.processQueue();
                return false;
            });
        },


        sending: function(file, xhr, formData) {
            formData.append("_token", $('meta[name="csrf-token"]').attr('content'));
            formData.append("foo", 'bar');   //  Test
        },

    });


In my contactController.php :


class ContactController extends Controller
{
    public function uploadFile(Request $request)
    {
        return response()->json($request->all());
    }
}


In my console :

!(http://img11.hostingpics.net/pics/738830Capturedecran20170214a112537.png)

Someone to help me at this point ? :(

12 Feb
1 year ago

fdusautoir left a reply on PHPStorm Automatic Reformat

@hendranucleo That's right. Just press enter and that reformat what I just wrote.

fdusautoir started a new conversation PHPStorm Automatic Reformat

Hi There,

This is my settings :

Settings

When I write a function in a php file for example, this is what I get :

function test() {
    return 'Hello World';
}

If I run Code > Reformat Code I get exactly what I want refers to my settings :

function text()
{
    return 'Hello World';
}

My question is : How to get this automatically when I'm writing ? That's very constraining to do it manually each time.

Thanks for you help . :)

08 Feb
1 year ago

fdusautoir left a reply on Laravel Mix And BrowserSync

Any help ? :(

06 Feb
1 year ago

fdusautoir left a reply on Laravel Mix And BrowserSync

Someone can help me ? :/

fdusautoir left a reply on Laravel Mix And BrowserSync

I think the module.exports.plugins is not the good way to achieve it

fdusautoir left a reply on Using Assets Like Images In App.scss (Has To Be Compiled By Webpack)

Put your images in your assets folder and define the url in your scss files relative to this path.

for example :

assets/sass/app.scss assets/images/back.jpg

body {
    background: url('../images/back.jpg');
}

All your images will be compiled in your public after after the run dev command.

fdusautoir left a reply on Using Nl2br() In A Controller

Have you tried this :


/**
   * Update the Assignment.
   *
   * @param  Request  $request
   * @return Response
   */
  public function update(Request $request, $id)
  {

    $assignment = Assignment::findOrFail($id);
    $assignment->brief = nl2br($request->brief); 
    $assignment->save();

  }

fdusautoir started a new conversation Laravel Mix And BrowserSync

Hi everybody !

I try to use browserSync with laravel Mix. Any errors with npm run watch but nothing appends when I update a a view file for example. I precise that I installed brothersync with npm install --save-dev browser-sync-webpack-plugin

Did I do a mistake in the webpack.mix.js file ?



const { mix } = require('laravel-mix');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');

const extract = [
    'jquery',
    'sweetalert',
    'vegas',
    'simplelightbox',
    'swiper',
];

mix.js([
    'resources/assets/js/home.js',
    'resources/assets/js/app.js',
    'resources/assets/js/contact.js',
], 'public/js/app.js')
    .extract(extract)
    .version();

mix.sass('resources/assets/sass/main.scss', 'public/css/all.css');

module.exports.plugins = new BrowserSyncPlugin({
    host: 'lvdp.dev'
});



Thanks for your help (I'm on the last version of Laravel. Updated yesterday).

fdusautoir left a reply on Flash Message With FormRequest

You're right ! Thanks a lot ! :)

05 Feb
1 year ago

fdusautoir started a new conversation Flash Message With FormRequest

Hi Everybody !

I attempt to pass a flash message when a form validation failed but I have an error. Validation is OK, I'm redirected to the form page with errors bag etc. but when I attempt to override the protected failedValidation() function, I have this following message : Class App\Http\Requests\sendContactRequest does not exist

What's wrong ?



<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class sendContactRequest extends FormRequest
{


    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'      => 'required',
            'phone'     => 'required',
            'email'     => 'required',
            'comment'   => 'required'
        ];
    }


    /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return mixed
     */

    protected function failedValidation(Validator $validator)
    {
        alert()->warning('oops ... error');
        return parent::failedValidation($validator);
    }

}

Thanks for your help :)

04 Feb
1 year ago

fdusautoir left a reply on Webpack Mix And Url()

Thanks a lot.

'Mix will look there for all your js/css/images/fonts and compile those to your public folder.'

I don't know it for your last answer and that is really great ! :-)

fdusautoir started a new conversation Webpack Mix And Url()

Hi there.

I've a problem with my my shell npm run dev command. Everything is working well but when it's time to compile my sass files, I've this error :


 ERROR  Failed to compile with 6 errors

These dependencies were not found in node_modules:

* ../images/load-2.svg
* ./overlays/02.png
* ../../fonts/lvdp/lvdp.eot
* ../../fonts/lvdp/lvdp.woff
* ../../fonts/lvdp/lvdp.ttf
* ../../fonts/lvdp/lvdp.svg

This is my webpack.mix.js :


const { mix } = require('laravel-mix');


mix.js([
    'resources/assets/js/vendor/modernizr.js',
    'resources/assets/js/vendor/classie.js',
    'resources/assets/js/vendor/sweetalert.js',
    'resources/assets/js/vendor/simple-lightbox.jquery.js',
    'resources/assets/js/vendor/vegas.js',
    'resources/assets/js/vendor/swiper.jquery.js'
], 'public/js/vendor.js')
    .version();

mix.js([
    'resources/assets/js/menu.js',
    'resources/assets/js/contact.js',
    'resources/assets/js/home.js',
    'resources/assets/js/newsletter.js'
], 'public/js/app.js')
    .version();

mix.sass('resources/assets/sass/main.scss', 'public/css/all.css');

And here it's my package.json



{
  "private": true,
  "scripts": {
    "dev": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "hot": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "production": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.15.2",
    "jquery": "^3.1.0",
    "laravel-mix": "^0.6.0",
    "lodash": "^4.16.2"
  }
}

That's seems to be with the use of url() in css. What is the way to say webpack to ignore url() value ?

Any help ? :)

20 Aug
2 years ago

fdusautoir started a new conversation Replicate Model With Relationships

Hi there,

I want to replicate a template with all his relations ships with Eloquent. I did this and it works like a charm :

$clone = $template->quote->replicate();
        $clone->push();

        foreach($template->quote->categories as $category)
        {
            $clone->categories()->attach($category);
        }
        
        foreach($template->quote->subcategories as $subcategory)
        {
            $clone->subcategories()->attach($subcategory, ['quote_category_id' => $subcategory->pivot->quote_category_id]);
        }
        
        foreach($template->quote->tasks as $task)
        {
            $clone->tasks()->attach($task, ['quote_subcategory_id' => $task->pivot->quote_subcategory_id]);
        }
        
        foreach($template->quote->subtasks as $subtask)
        {
            $clone->subtasks()->attach($subtask, ['quote_task_id' => $subtask->pivot->quote_task_id]);
        }

        $clone->push();

Now, I want to do a little bit of refactoring and make it more easier. I try this but when I push at the end, only the quote line is replicate and not all the relations that I loaded before :

$quote     = $template->quote->load('categories','subcategories', 'tasks', 'subtasks');
        $new_quote = $quote->replicate();
        $new_quote->push();

How to have the same result as above with this solution ?

15 Aug
2 years ago

fdusautoir left a reply on Convention Tables Naming

@FrancescoZaffaroni You're right. It's a great work to change all the database but it's worth it. :)

fdusautoir left a reply on Convention Tables Naming

@simondavies @SaeedPrez @FrancescoZaffaroni The basics laravel conventions are greats for simple database. In this case, I prefix categories with quotes_ because it deals with quotes. In this database, I have others categories tables which are attached to their parents. For example, specifications_categories.

In this case and to follow your advices, I have now :

  • quotes
  • quotes_categories
  • category_quote ( to follow Laravel conventions)

Then I have 2 models :

  • Quote
  • QuoteCategory

In the Quote Model I have :

public function categories() 
    {
        return $this->belongsToMany('QuaiDesBalises\QuoteCategory', 'category_quote', 'quote_id', 'category_id');
    }

If I don't specify the pivot table I have this error :

Table 'quote_quote_category' doesn't exist

Then, when I specify the pivot table and not the local and foreign keys, I have this error :

Unknown column 'category_quote.quote_category_id' in 'field list

To finish, when I specify the pivot table and the local / foreign keys, that's works. So, if we follow Laravel, we should have this database :

quotes

  • id
  • name

quotes_categories

  • id -name

quote_quote_category

  • quote_id
  • quote_category_id

Finally, we can consider that Laravel except to be accurate in the naming of fields in pivot tables

fdusautoir started a new conversation Convention Tables Naming

Hi there,

I want to have your opinion about convention naming for database tables.

EXAMPLE :

quotes *id *name

quotes_categories *name *desc

**quotes_has_categories ** *quote_id *quote_category_id

**The question is simple : ** In the quotes_has_categories table, what's the best way to name the foreign key for the category id : quote_category_id or category_id.