baguus

baguus

Member Since 2 Years Ago

Experience Points 850
Experience Level 1

4,150 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 0
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • 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.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    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.

25 Jul
11 months ago

baguus left a reply on Multiple Relationships Between Same Tables.. Naming And Syntax

Allrighty :) Thank you, this is along the lines I was searching/expecting. Too bad its not in 5.4 version :)

baguus left a reply on Multiple Relationships Between Same Tables.. Naming And Syntax

Hi Cinek Thanks for the reply. Yes this was the main problem. By default I don't have this field set. I already got my answer here. The solution was to check if the field is set. I would still like to know if there is a simple way to prepare the collection in the controller so I would get empty string "" if the main_distributor_id field is null. I know I can build the query with the query builder. But I was wondering if there is an eloquent way to do it.

baguus started a new conversation Multiple Relationships Between Same Tables.. Naming And Syntax

Hi everyone, I have 2 tables (users and companies). Users have different roles (shopper, distributor, administrator,...). I have a working solution for shoppers and partially for distributors. I'm having a problem using eloquent to setup the second relationship for distributor users. In users table I have company_id key for shoppers In companies table I have main_distributor_id key for distributors

Relations: One company can have multiple shopper users. One shopper user can be asigned to one company.

One company can have one distributor. One distributor can be asigned to multiple companies.

User model:

/* used for shoppers */
public function company() {
        return $this->belongsTo(Company::class);
}

/* what is the proper naming? */
public function mainDistributorCompanies() {
        return $this->belongsTo('App\Company','main_distributor_id','id');
}

Company model:

/* for shopper users.. */
public function users() {
        return $this->hasMany(User::class, 'company_id');
}

/* What is the proper naming */
public function mainDistributorUsers() {
        return $this->hasOne('App\User','id','main_distributor_id');
}

Companies controller:

public function index(Request $request) {

/* is this the correct way to include the relationship? Naming? */
$companies = Company::with('mainDistributorUsers')->get();
return view('companies/index', compact('companies'));
}

Companies index view:

@foreach($companies as $company)
    <tr>
        <td>{{ $company->index }}</td>
                <td>{{ $company->name }}</td>
                <td>{{ $company->address }}</td>

        <td>{{ $company->mainDistributorUsers->username }}</td> // error
        <td>{{ $company->mainDistributorUsers()->username }}</td> // error
        <td>{{ $company->username }}</td> // empty
    </tr>
@endforeach

Did I choose the wrong relationship for distributors? Wrong naming?

05 Jul
1 year ago

baguus started a new conversation Code Organisation - Architecture

Hi guys

I'm wondering on how to organize my code. I wrote this niffty widget for my application. I put the controller logic for the widget in a service provider as I need it on the dashboard (home) for a certain user. Now I need similar widgets elsewhere in the application. Do you think its better to write the loginc for other widgets in the service providers or would you rather use model controllers or perhaps helper class for such a task? For this tasks I don't really need service providers. But if someone was to take over the project, where would he/she look first?

BR, Igor

30 May
1 year ago

baguus left a reply on Multiselect Dropdown On Belongstomany

I think I got it :)

scope

public function scopeOfRole($query, $role) {
        return $query->
        join('role_user', 'role_user.user_id', '=', 'users.id')->
        join('roles', 'roles.id', '=', 'role_user.role_id')->
        select(
            DB::raw('GROUP_CONCAT(users.first_name," ",users.last_name) as username'),
            'users.id')->
        where('roles.name', $role)->
        groupBy('users.id');
}

controller

public function edit(Request $request, $id) {

$company = Company::findOrFail($id);
$users = User::OfRole('my role')->pluck('username','users.id')->all();

return view('companies.edit', compact(['company','users']));

edit view

{!! Form::select('users[]', $users, $company->users()->pluck('users.id'), ['class' => 'form-control', 'multiple' => 'multiple']) !!}

baguus started a new conversation Multiselect Dropdown On Belongstomany

Hi everyone. I'm.. complicating but: I want to populate a multi select dropdown with users that have a specific user role I have 5 tables (users, role_user, roles, companies and company_user)

Model relations

App\User:

public function roles()
    {
        return $this
            ->belongsToMany('App\Role')
            ->withTimestamps();
    }


    public function companies()
    {
        return $this
            ->belongsToMany('App\Company')
            ->withTimestamps();
    }


App\Role:
    public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }


App\Companies:
    public function users()
    {
        return $this->belongsToMany('App\User');  // with user_role ??
    }

CompaniesController

public function edit(Request $request, $id) {

$company = Company::findOrFail($id);

$users = User::where('role_id',4)->pluck('username')->all(); // no role_id column
$users = User::pluck('username','id')->all();  // returns all without selected

return view('companies.edit', compact(['company','users']));
}

public function update(Request $request, $id) {
    /* TODO */
}

Edit view


{!! Form::select('users[]', $users, null, ['class' => 'form-control', 'multiple' => 'multiple']) !!}


Do I need to create another connecton between companies and roles? I need to display only the users that have a specific user role.

Subquestion: Is there a simple way to concatenate First name + Last name instead od username in the dropdown?

31 Mar
1 year ago

baguus left a reply on Web And Api Authentication Middleware

Thank you. I had this idea that all api call should go through api.php I still need to double check with Postman but Auth::check() works now :)

baguus started a new conversation Web And Api Authentication Middleware

Hi everyone. sorry for the "undefined" title. I don't know how to phrase is correctly. I have a view in my app that is accessible to authenticated users.

web.php

Route::get('/orders/complete', [
    'as' => 'completeOrders', 'uses' => '[email protected]']);

OrdersController.php

    public function completeOrders(Request $request)
    {
        if (!Auth::check()) {
            return redirect('/');
        }
        $request->user()->authorizeRoles(['admin']);

        $orders = Order::CompleteOrders(AppHelper::instance()->getCurrentSeason())->get();
        return view('orders.complete', compact('orders'));
    }

View

<meta name="csrf-token" content="{{ csrf_token() }}"/>

<table id="completeorders">
    <thead>
            <tr>
                    <th>Order ID</th>
            <th>Country</th>
            <th>Company name</th>
            <th class="check">Confirmed</th>
            <th>View</th>
        </tr>
    </thead>
    <tbody>
    @foreach ($orders as $order)
        <tr>
            <td>{{ $order->id}}</td>
            <td>{{ $order->country }}</td>
            <td>{{ $order->name }}</td>
            <td>{{ Form::checkbox($order->id, $order->id, $order->confirmed, ['class' => 'checkbox fa-fw', 'id' => $order->id]) }} </td>
            <td><a href="{{ url('orders/cartcomplete/' . $order->id) }}"><i
                                                class="fa fa-search fa-fw"></i></a></td>
        </tr>
    @endforeach 
    </tbody>
</table>

my.js

$(document).ready(function () {

$('#completeorders').on('click', 'input[type="checkbox"]', function (e) {

        var isChecked = $(this).is(':checked');
        e.preventDefault();
        
        var checked = '';
        var dataId = $(this).val();
        var myid = "#" + dataId;

        var url = window.location.protocol + "//" + window.location.host + "/" + 'api/orders/complete';
        var token = $('meta[name="csrf-token"]').attr('content');
        
    $('html, body').css("cursor", "wait");
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            type: 'POST',
            url: url,
            dataType: 'JSON',
            data: {
                "_method": 'POST',
                "_token": token,
                "id": dataId,
                "isChecked": isChecked
            },
            context: this,
            success: function (response) {
                console.log('success');
        console.log(response[0].successful);
        $(this).prop("checked", isChecked);
                $('html, body').css("cursor", "auto");
            },
            error: function (e) {
              //  console.log(e.responseText);
                $(this).prop("checked", !isChecked);
        $('html, body').css("cursor", "auto");
            }
        });
    });

});

Kernel.php

 protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

        'api' => [
        //    \Illuminate\Session\Middleware\AuthenticateSession::class,
        //    \App\Http\Middleware\VerifyCsrfToken::class,
            'throttle:60,1',
            'bindings',

        ],
    ];


    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\Admin::class, 
        'ajax' => \App\Http\Middleware\AllowOnlyAjaxRequests::class,
    ];

VerifyCsrfToken.php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //   'ajax/*',
    ];

    protected function tokensMatch($request)
    {
        $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
        return $request->session()->token() == $token;
    }
}

api.php

Route::post('orders/complete', '[email protected]');

ConfirmatonController.php

 public function confirm(Request $request) {

return response()->json(array(['successful' => 'Response ok!']));

So up to here the api call works but is not verified.

How do I verify/authenticate this api call?

If I change my api.php to

Route::group(['middleware' => ['web']], function () {
    Route::post('orders/complete', '[email protected]');
});

i get 408 TokenMismatchException

How can I verify this correctly. I want to allow the post call only if the user is logged in.

30 Nov
1 year ago

baguus left a reply on Download Starts Before The File Is Created

If anyone experiences the same problem. I forgot to add ->close() when I create the .zip file

$zipper->make('temp/Orders.zip')->add($files)->close();

baguus started a new conversation Download Starts Before The File Is Created

Hi guys, I want to create 1 - 10 excel files, compress them to .zip and download. I use maatwebsite/excel to create the files and store them in the temporary folder and this works. I use Zipper to zip the files in the temporary folder and download them. I get the error that the zipped file doesn't exist. If I run the download again (press the download button) the file is downloaded.

How can I "delay" the download until the .zip file is actually created?

Is there a better procedure to complete this task? It would be best if I didn't have to store the files on server at all as I need to delete them after the task.

24 Oct
1 year ago

baguus left a reply on Belongstomany, HasMany Relationship Back On Same Table

Arrr of course I tried to complicate instead of trying the most obvious one. Thank you for this. Now I need to solve the other side :) I'll ask again if I get stuck.

baguus left a reply on Belongstomany, HasMany Relationship Back On Same Table

Hi Thank you for your answer. I think I blundered in the controller. I got the the sponsoring company collection and the the budgets they sponsor to my view. I'm still a bit unclear on how to add sponsored company names though. Shoud I add them to collection in the foreach loop in the controller or is there an elegant way to do display them from $company->sponsors?

Relations

public function sponsors() {
   return $this->belongsToMany('App\Company','company_sponsors','company_id','sponsor_id')->withPivot('budget','sponsor_id');
}

public function companies() {
  return $this->belongsToMany('App\Company','company_sponsors','sponsor_id','company_id')->withPivot('budget','company_id');
}

controller

$company = Company::find($companyId);
$company_sponsored = $company->sponsors; // add sponsored company data here?

return view('companies/sponsor', compact('company','company_sponsored'));

view

My company {{ $company->name }}
@foreach($company->sponsors as $sponsor)
Sponsored company ID: {{ $sponsor->pivot->sponsor_id}}    
Sponsored budget:  {{ $sponsor->pivot->budget }}
// can I add the sponsored company name to this collection?

Thank you for your time

baguus started a new conversation Belongstomany, HasMany Relationship Back On Same Table

Hi guys I'm trying to build relationships between companies and company_budgets table. In company table I have an id and in company_budgets I have id, company_id, sponsor_id and budget. What I want are to acheive is: One company can sponsor multiple companies in the same table and one company can be sponsored by multiple companies. How should I create the relationships?

My failed attempts:

public function sponsors() {
return $this->belongsToMany('App\Company','company_sponsors','company_id','sponsor_id')->withPivot('budget');
}

public function companies() {
return $this->hasMany('App\Company','company_sponsors','sponsor_id','company_id')->withPivot('budget');
}

And the next question would be, how can I query the pivot table?

26 Sep
1 year ago

baguus left a reply on Return Back To Edit Form With Old Url

I have edited the code a bit

@if(url()->current() != URL::previous())
    @if(Session::has('myreferrer'))
            {{ Session::forget('myreferrer') }}
    @endif
        {{ Session::put('myreferrer', URL::previous()) }}  // Seems that this executes every time..
    <a href="{{ URL::previous() }}" class="btn">Cancel</a>
@else
<a href="{{ Session::pull('myreferrer') }}" class="btn">Back</a>
@endif

baguus started a new conversation Return Back To Edit Form With Old Url

Hi guys I'm trying to add a funcionality to return back after several edits. I want to add a Back button to edit form after update. When a user selects edit (from list of products or from single product) edit form is shown. At the end there is a Cancel button with {{ URL::previous() }}. This works.

After user completes first edit I return to edit form with flash message of success. I then change the "Cancel" button to "Back". I compare current and previous url. This works.

Now I have a problem on how to set the original url. I tried setting it in session. And it works in first iteration. In second iteration it gets overwritten.

I tried with setting the url in form request, but that didn't work as desired either. The url gets overridden.

Is there some nice way to acheive this?

in my edit.blade I have

@if(url()->current() != URL::previous())
    @if(!Session::has('myreferrer'))
        {{ Session::put('myreferrer', URL::previous()) }}
    @endif
        <a href="{{ URL::previous() }}" class="btn">Cancel</a>
@else
    <a href="{{ Session::pull('myreferrer') }}" class="btn">Back</a>
@endif

This works with "button" but not with url.

Yes I know best practice would be to return to previous page after edit... :)

10 Sep
1 year ago

baguus started a new conversation Call To A Member Function AuthorizeRoles() On Null After Session Timeout

Hi guys I have a problem on how to catch a session timeout.

I have a function in my User model:

public function authorizeRoles($roles)
    {
        if ($this->hasAnyRole($roles)) {
            return true;
        }
        abort(401, 'This action is unauthorized.');
    }

In controller function

public function someFunction(Request $request) {
        $request->user()->authorizeRoles(['some_user_role']);
}

in Handler.php

public function render($request, Exception $exception)
    {

        if ($exception instanceof NotFoundHttpException) {
            return response()->view('error/404', [], 404);
        }

    /*    if ($exception->getStatusCode() == 401) {
            return response()->view('error/401', [], 401);
        }  gives white screen if session expired */
        return parent::render($request, $exception);
    }

When the session expires I get a

FatalThrowableError Call to a member function authorizeRoles() on null

here

$request->user()->authorizeRoles(['some_user_role']);

I guess the object doesn't exist anymore? How can I catch session timeout correctly. I would like to redirect to login or show a session expired page.

24 Aug
1 year ago

baguus left a reply on Passing Custom Query Results To Layout Template Part

Great I think this will work. I get the variable through to my view. I guess I had a typo somewhere - I'm sure I tried this before. Thank you

baguus started a new conversation Passing Custom Query Results To Layout Template Part

Hi I'm a bit confused on how to do this. I have a template part (budget.blade.php) that I'm including in my template (@include). I need to get variables from a custom query based on user into this template part . (users company budget, orders total,...). I tried with a Service provider

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;
use App\Order;
use App\Product;
use App\Company;
use Auth;

class BudgetServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer('layouts.budget', function () {
            // Can I perform my queries here and if how do I pass them to layouts/budget.blade.php?
        });

    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

Partial view

<div class="budget-info-wrapper">
    <div class="budget">
        Forseen budget: {{ $var1}}
    Order total: {{ $var2}}
    Difference: {{ $var3}}      
    </div>
</div>

Is this the correct way and If so, how do I pass the variables to my template part?

17 Aug
1 year ago

baguus left a reply on ORM BelongsToMany Data Handling

I found the problem :) I was writing the wrong productId to product_order pivot table. I get the data now. Except the quantity (additional field in pivot table)

baguus left a reply on ORM BelongsToMany Data Handling

Arr I think the pivot table in order model was defined incorrectly. I changed it to pivot table fields. I still keep getting an empty array.

baguus left a reply on ORM BelongsToMany Data Handling

Hi I tried that. I get an empty array.

object(Illuminate\Database\Eloquent\Collection)[364]
  protected 'items' => 
    array (size=0)
      empty

baguus started a new conversation ORM BelongsToMany Data Handling

Hi everyone I'm a bit stuck with displaying data from many to many related data. I know this must have been answered many times but I can't find the right answer for me. I have 5 tables: users, orders, products and the pivot tables user_order and order_product.

Model relations

User

public function orders() {
        return $this
            ->belongsToMany('App\Order')
            ->withTimestamps();
}

Order

public function products() {
        return $this ->belongsToMany('App\Product','product_order')->withPivot('product_id','order_id','quantity')
->withTimestamps();
}

public function users() {
    return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
}

Product

public function orders() {
        return $this
->belongsToMany('App\Order','product_order')->withPivot('order_date','status','status_change','comments')
->withTimestamps();
}

OrdersController

// Adding Items - This works. Is this the correct approach or is there a "better" way?

public function additem(Request $request) {

$order = Order::findOrFail($orderId);

$order->products()->save($order, [
                    'product_id' => $request['productId'],
                    'order_id' => $request['orderId'],
                    'quantity' => $request['quantity']]);

return back();
}

// display cart

public function show(Request $request, $userId) {

//  1. TODO get order ID from user ID

// get data 

$orders = Order::with('products')->findOrFail(1);
// I'm stuck here. Do I need a separate query to get all products from specific order?

return view('orders/view', compact('orders'));
}

View

<h1>Order {{ $orders->id }}<h1>

@foreach ($orders as $order)

Product id: {{ $order->products()-> index}}
Product name: {{ $order->products()-> name}}
Product price: {{ $order->products()-> price}}
Quantity: {{ $order->products()-> quantity}}  // can this be mixed?
Total: {{ ($order->products()-> quantity * $order->products()->price }}

@endforeach 

How can I get all the data of a specific order? (Product id, Product name, Product price, Quantity) ?

Thank you for your time.

31 Jul
1 year ago

baguus left a reply on ORM Scope Query With Left Join And Group_concat

I'm not sure if this is the best practice but this works :)

public function scopeCompanies($query) {
        return $query
    ->leftJoin('users', 'company_id', '=', 'companies.id')->
        select(
            DB::raw('GROUP_CONCAT(username) AS Users'),
        'companies.index AS Index',
            'companies.name AS Company Name',
            'companies.address AS Address')
            ->groupBy('companies.index')
            ->orderBy('Users','DESC')
            ->get();
}

baguus started a new conversation ORM Scope Query With Left Join And Group_concat

Hi guys I want to prepare queries for Excel download. I have 2 models. User and Company with belongsTo/hasMany relationship. User belongs to one company and company can have many users (or none).

I have relations defined

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

/* Company model */
public function users() {
        return $this->hasMany(User::class, 'company_id');
}

I want to produce a query like this

SELECT companies.`name` AS "Company Name", companies.address AS "Company Address",
GROUP_CONCAT(users.username) AS "Users"
FROM Companies
LEFT JOIN users ON users.company_id = companies.id
GROUP BY companies.`name`

Can this be acheived with Laravel ORM or would it be better to write query directly

Something like single model query?

public function scopeUsers($query) {
        return $query->select(
        'companies.name AS Company Name',
        'companies.address AS Company Address')->get();
}

// Can I add LEFT JOIN and GROUP_CONCAT here?
10 Jul
2 years ago

baguus left a reply on ORM Select Model With Related Data And View

Aaaaaaa

// id here should be companies_id, i.e. the foreign key on the users table

I was looking this the other way around :) Thank you. I think I'll change it to singular as per convetion.

baguus left a reply on ORM Select Model With Related Data And View

Hi all Thank you for your answers. I got roles working. Companies are working, but I'm getting the wrong company for specific user. I guess I need to correct the relations and singular/plural naming.

@Snapey Does Laravel know how to correctly turn singular to plural e.g. companY -> companIES and vice versa?

baguus started a new conversation ORM Select Model With Related Data And View

Hi I've been battling the next orm fight. I want to show data from 3 related tables. user, roles, companies and role_user pivot table.

User model

public function roles() {
    return $this
            ->belongsToMany('App\Role')
            ->withTimestamps();
}

public function Companies() {
    return $this->belongsTo(Companies::class, 'id');
}

Role model

public function users() {
    return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
}

Companies model

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

UsersController

public function show(Request $request, $id) {

// $user = User::findOrFail($id); <- gets data from user model without companies and roles

// nth attempt..
$user = User::with('roles','companies')->findOrFail($id);

// How do I retrieve/add/join data from companies and roles for specific user?

return view('users.view', compact(['user']));

view

Username: {{ $user->username }}

Email: {{ $user->email }}

Company: {{ $?????->????->company_name  }}

Roles: @foreach ($????? as $role)
{{ $role->name  . ',' }}
@endforeach 

How to correctly add/append the related data and print it out on view? Thank you

07 Jul
2 years ago

baguus left a reply on Update Pivot Table Once Again

Not a problem. I did get the chance to learn the right way to call the model :) I must say though, that I cannot find the example on how to retreive the model with related data (user with user role)

this

$users = User::with('roles','companies')->findOrFail($id);

was a more or less a lucky guess.

Anyway, thank you for your help. I'm sure I'll have more basic questions in the future.

06 Jul
2 years ago

baguus left a reply on Update Pivot Table Once Again

hmm I must be missing something..

firstOrFail() returns the first record found in the database. If no matching model exist, it throws an error.

So if I understand correctly firstOrFail() does not take an attribute $id If I use firstOrFail($id) i get:

Type error: Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given at Grammar->columnize('6') in Grammar.php (line 131)

findOrFail($id) takes an id and returns a single model. If no matching model exist, it throws an error.

This one works for me. So I would say find is the correct one, not first

If I'm wrong I need more tutoring :)

05 Jul
2 years ago

baguus left a reply on Update Pivot Table Once Again

I think I got it working :)

@bobbybouwmann Is this a typo "$user = User::firstOrFail($id);" ? If so, could you edit your reply so I can accept it as the correct answer? Thank you

controller

public function edit(Request $request, $id) {

// for dropdown items
$companies = Companies::all()->pluck('name', 'id');
$roles = Role::pluck('name','id')->all();

// my user data
$users = User::with('roles','companies')->findOrFail($id);

return view('users.edit', compact(['users', 'roles', 'companies']));
}


public function update(Request $request, $id) {

$user = User::findOrFail($id);
        $user->update([
            'first_name' => $request['first_name'],
            'last_name' => $request['last_name'],
            'email' => $request['email'],
            'companies_id' => $request['companies'],
        ]);

        $user->roles()->sync($request->get('roles'));

    return redirect('users');
}

view


{{ Form::select('roles', $roles, $users->roles()->pluck('roles.id'), ['class' => 'form-control']) }}

baguus left a reply on Best Way To Install And Use Bootstrap

Hi I think best practice is the one that works for you. If you install it through composer you end up with additional files..

baguus left a reply on Update Pivot Table Once Again

Hi I think I'm missing something. If I call

public function edit(Request $request, $id) {
    
$user = User::firstOrFail($id);

}

I get

Type error: Argument 1 passed to Illuminate\Database\Grammar::columnize() must be of the type array, string given..

at at Grammar->columnize('6')in Grammar.php (line 131)

Do I need to define something else in my model besides

protected $table = 'users';

and the relations?

04 Jul
2 years ago

baguus left a reply on Update Pivot Table Once Again

Hi Thank you for your answer. I guess I went the wrong way :)

contoller

public function edit(Request $request, $id) {
    $roles = Role::all()->pluck('name', 'id');
    $companies = Companies::all()->pluck('name', 'id');
    $users = DB::table('users')
                ->join('companies', 'users.companies_id', '=', 'companies.id')
                ->join('role_user', 'role_user.user_id', '=', 'users.id')
                ->join('roles', 'roles.id', '=', 'role_user.role_id')
                ->select('users.id', 'users.username', 'users.first_name', 'users.last_name', 'users.email', 'companies.name AS company', 'roles.name AS user_role', 'roles.id AS role_id', 'users.companies_id')
                ->where('users.id', '=', $id)
                ->first();

            return view('users.edit', compact(['users', 'roles', 'companies']));
}



view

                    {!! Form::open(['action' => ['[email protected]', $users->id],'class'=> 'form-horizontal']) !!}
                    {{ csrf_field() }}

                        <div class="col-md-9">
                            <input id="name" type="text" class="form-control" name="name" value="{{ $users->username }}"
                                   required disabled>

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

                    <div class="form-group{{ $errors->has('role') ? ' has-error' : '' }}">
                        <label for="role" class="col-md-3 control-label">User role</label>
                        <div class="col-md-9">
                            {{ Form::select('roles', $roles, $users->role_id, ['class' => 'form-control']) }}
                        </div>
                    </div>

                    <div class="form-group{{ $errors->has('companies') ? ' has-error' : '' }}">
                        <label for="companies" class="col-md-3 control-label">Company</label>
                        <div class="col-md-9">
                            {{ Form::select('companies', $companies, $users->companies_id, ['class' => 'form-control']) }}
                        </div>
                    </div>
.
.
.
                                <button type="submit" class="btn btn-primary pull-right">
                                    Update
                                </button>


{!! Form::close() !!}

baguus started a new conversation Update Pivot Table Once Again

Hi I know this question was asked and answered already but I cant find the working solution. I have 3 tables: users, roles, role_user

users model

public function roles()
    {
        return $this
            ->belongsToMany('App\Role')
            ->withTimestamps();
    }

roles model

    public function users()
    {
        return $this
            ->belongsToMany('App\User')
            ->withTimestamps();
    }

controller

public function update(Request $request, $id)
    {

$user = DB::table('users')
            ->where('id', $id)
            ->update([
                'first_name' => $request['first_name'],
                'last_name' => $request['last_name'],
                'email' => $request['email'],
                'companies_id' => $request['companies'],
            ]);

// How to update the record in role_user table?
  
return redirect('/');
}

Is there a simple way to update the record in role_user table? I was trying with detach(), attach(), sync(),...