BartHuis

BartHuis

Member Since 3 Years Ago

Wognum

Programmer at Keukenmagazijn

Experience Points 8,900
Experience Level 2

1,100 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 40
Lessons
Completed
Best Reply Awards 1
Best Reply
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.

01 Mar
1 year ago

BartHuis left a reply on Make An Empty Relation

thanks @Snapey don't need it anymore, also posted that as last post...

09 May
2 years ago

BartHuis left a reply on "Drop All Tables" Instead Of "migration Rollback"

Thanks! if you have multiple connections, you can use this:


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use \DB;

class DropDb extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dropdb {database}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'drops all tables of specific or all connections';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $database = $this->argument('database');
        
        if($database == "all") {
            $databases = array("mysql", "connection2", "connection3");
        }
        else{
            $databases = array($database);
        }
        foreach ($databases as $databasetoempty) {
            $pdo = \DB::connection($databasetoempty)->getPdo();
    
            $tables = $pdo
                ->query("SHOW FULL TABLES;")
                ->fetchAll();
    
            $sql = 'SET FOREIGN_KEY_CHECKS=0;';
    
            foreach ($tables as $tableInfo) {
                // truncate tables only
                if ('BASE TABLE' !== $tableInfo[1])
                    continue;
        
                $name = $tableInfo[0];
                $sql .= 'DROP TABLE ' . $name . ';';
                $this->info('Dropping table ' . $name);
            }
    
            $sql .= 'SET FOREIGN_KEY_CHECKS=1;';
    
            $pdo->exec($sql);
        }
    }
}


now you can do:

php artisan dropdb all

or

php artisan dropdb connection2
03 May
2 years ago

BartHuis left a reply on Make An Empty Relation

hmm, thanks for the help, but today we decided to skip this. You could better just let the model always refer the relation, and make an empty table. (or in our case, it would be an empty view, we make multiple environments with database views for every environment, what we wanted is to not make a view if in that environment it isn't used, now we'll just make an empty view, so the model thinks there just nothing related...)

02 May
2 years ago

BartHuis left a reply on Make An Empty Relation

good idea, but when i build it automatic with php storm:

<?php
/**
 * Created by PhpStorm.
 * User: Bart
 * Date: 2-5-2017
 * Time: 16:03
 */

namespace App\Custom;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Relation;

class EmptyRelation extends Relation
{
    
    /**
     * Set the base constraints on the relation query.
     *
     * @return void
     */
    public function addConstraints()
    {
        // TODO: Implement addConstraints() method.
    }
    
    /**
     * Set the constraints for an eager load of the relation.
     *
     * @param  array $models
     * @return void
     */
    public function addEagerConstraints(array $models)
    {
        // TODO: Implement addEagerConstraints() method.
    }
    
    /**
     * Initialize the relation on a set of models.
     *
     * @param  array $models
     * @param  string $relation
     * @return array
     */
    public function initRelation(array $models, $relation)
    {
        // TODO: Implement initRelation() method.
    }
    
    /**
     * Match the eagerly loaded results to their parents.
     *
     * @param  array $models
     * @param  \Illuminate\Database\Eloquent\Collection $results
     * @param  string $relation
     * @return array
     */
    public function match(array $models, Collection $results, $relation)
    {
        // TODO: Implement match() method.
    }
    
    /**
     * Get the results of the relationship.
     *
     * @return mixed
     */
    public function getResults()
    {
        // TODO: Implement getResults() method.
    }
}

and put this in the else:

return New \App\Custom\EmptyRelation();

i'll get:

Type error: Too few arguments to function Illuminate\Database\Eloquent\Relations\Relation::__construct(), 0 passed

and when putting $this in:

return New \App\Custom\EmptyRelation($this);

i'll get:

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\Relation::__construct() must be an instance of Illuminate\Database\Eloquent\Builder, instance of App\Testmodel given

BartHuis started a new conversation Make An Empty Relation

hi, i would like to make an empty relation, is that possible?

tried

class Testmodel extends Model
{
    /**
     * Get the testrelation records associated with the testmodel.
     */
    public function testrelations()
    {
        if ($envoirementcheck == TRUE ) {
            return $this->belongsToMany('App\Testrelation');
        } else {
            return null;
        }
        
    }

then i'll get:

Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

so also tried it this way:

class Testmodel extends Model
{
    /**
     * Get the testrelation records associated with the testmodel.
     */
    public function testrelations()
    {
        if ($envoirementcheck == TRUE ) {
            return $this->belongsToMany('App\Testrelation');
        } else {
            return New \Illuminate\Database\Eloquent\Relations\Relation;
        }
        
    }

but then i'll get

Cannot instantiate abstract class Illuminate\Database\Eloquent\Relations\Relation

any way to get this done?

and no, i can't just make the relation return nothing, because the envirement check is build in becouse i dont have the related database on certain envoirements. so if i'll just do:

class Testmodel extends Model
{
    /**
     * Get the testrelation records associated with the testmodel.
     */
    public function testrelations()
    {
            return $this->belongsToMany('App\Testrelation');
       
    }

i'll get:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'envoirementdb.testrelation' doesn't exist

so that's why i don't want the relation to be made in the model when i'm a certain envoirement.

Thanks, Bart

05 Apr
2 years ago

BartHuis started a new conversation Anyone Using Intervention/imagecache ? It's Not Working?

Is anyone using Intervention/imagecache ? it's not working? it should be especialy for laravel, and could be used standalone too? https://github.com/Intervention/imagecache/issues/80#issuecomment-291720120

07 Mar
2 years ago

BartHuis left a reply on Getting Current Namespace In Model?

if anyone comes here, i ended up using this:

$isAdmin = (substr(Route::getFacadeRoot()->current()->uri(), 0, 6) == 'admin/') ? 'admin' : '';

06 Mar
2 years ago

BartHuis left a reply on Getting Current Namespace In Model?

@SaeedPrez yeah, sorry, thats mostly the same in our case, but yes, i would like it as the namespace instead of the phisical route. but then it's the same question: the reason i want it, is to use the variable for something diferent is the real production mode, don't think a debug backtrace is the right way to find out if i'm in an admin namespace in a laravel model?

if it's not simple, the route is a good option, but not the best i think

BartHuis left a reply on Getting Current Namespace In Model?

@SaeedPrez i will try, but, the reason i want it, is to use the variable for something diferent is the real production mode, don't think a debug backtrace is the right way to find out if i'm on an admin route in a laravel model?

BartHuis left a reply on Getting Current Namespace In Model?

no: [11:07:14] LOG.info: test:Illuminate\Database\Eloquent\Model info log

it get its own, not the one that is calling it

BartHuis started a new conversation Getting Current Namespace In Model?

i have the following route>controller>model setup (cleaned up, only the rows needed for this problem)

//routes/web.php:
    include("admin.php");

//routes/admin.php:
    Route::group([ 'namespace' => 'Admin\\'.ucfirst(env('APP_TYPE')),'middleware' => 'auth','prefix' => '/admin'], function() {
        include("categories.php");
    });

//routes/categories.php:
    Route::get('/{categoryname}', ['as' => 'categoryurlbyname', 'uses'=>'[email protected]']);

//app/Http/Controllers/Admin/Apptype/CategoryController.php:
    public function categoryByNameView(Request $request){ //
        $categoryname = \Request::get('categoryname');
        $category = \App\Category::whereTranslation('path', $categoryname)->with('products')->firstOrFail();
        return view('category', ['category'=>$category,'ancestors'=>$ancestors]);
    }

//app/Category.php:
in a function:
    Log::info("test:".__NAMESPACE__);

the last one gives the namespace app instead of app/admin/apptype

how can i check if i'm admin in de model?

I know this may seem complex, but i left away much code, yes, we really need this structure, for reasons...

Bart

14 Nov
2 years ago

BartHuis left a reply on PDO Connection To Odbc Quits Without Error, Odbc_connect Works

Just another bump. Someone please?

10 Nov
2 years ago

BartHuis started a new conversation PDO Connection To Odbc Quits Without Error, Odbc_connect Works

Hi,

We're expecting problems on a odbc connection bt pdo, while it works well directly.

Example:

[email protected]:~/Code/project$ php artisan tinker
Psy Shell v0.7.2 (PHP 7.0.12-1+deb.sury.org~xenial+1 — cli) by Justin Hileman
>>> $connection = DB::connection('odbc');
[email protected]:~/Code/project$

when we try to make an connection to odbc, its failing and directly it quits tinker, but the odbc connection must be available in PDO when we show the drivers:

>>> PDO::getAvailableDrivers()
=> [
     "mysql",
     "odbc",
     "pgsql",
     "sqlite",
   ]

but the connection itself is working, because when we do this, it works (just replaced some queries and data into fake ;) ):

>>> $test = odbc_connect("test-connector","usename","password")
=> odbc link resource #484
>>> $query = "select query";
=> "select query"
>>> $result = odbc_do($test,$query);
=> odbc result resource #485
>>> while($row=odbc_fetch_array($result)){echo $row['field1'].'->'.$row['field2'];}
content1   -> content2 content1a   -> content2a content1b   -> content2b  content1c   -> content2c 

Put connection by PDO won't work. even when checking the connection error log at: var/log/php7.0-fpm.log we don't get any error, but still it quits tinker without an error message.

Does anyone knows what can be the problem in the pdo connection, or how to get any error back?

even tried this one in tinker:

>>> try { $results = \DB::connection("odbc") ->select(\DB::raw("query here")) ->first();  } catch(\Illuminate\Database\QueryException $ex){ dd($ex->getMessage()); }

but it keeps quiting tinker without any error, not in the var/log/php7.0-fpm.log and not in the standard laravel log :(

Hope anyone can help us.

Bart

03 Nov
2 years ago

BartHuis left a reply on Forelse Doesn't Seem To Work?

solution from github:

@forelse ($category->categoryGallery ?: [] as $image) <img src="{{$image["thumb_link"]}}" /> @empty @endforelse

this is working well

BartHuis left a reply on Forelse Doesn't Seem To Work?

hmmm, then i'll add the empty function around it, would be nice if the empty case would be true if the viarable doesn't excist too...

BartHuis left a reply on Forelse Doesn't Seem To Work?

dd is only for php, not for blade. i know it's working when it gets it's data. the problem is when it's empty, it should just skip it...

BartHuis left a reply on Forelse Doesn't Seem To Work?

Parse error: syntax error, unexpected 'endif' (T_ENDIF)

"has more than 1 value" ? the whole idea is that if it doesnt exist, i dont want errors to show but just skip it and go on with the rest of the page. just as it happens when i put an @if(! empty( around it?

BartHuis started a new conversation Forelse Doesn't Seem To Work?

Hi, When i do this:

            @if(! empty($category->categoryGallery))
                @forelse ($category->categoryGallery as $image)
                    <img src="{{$image["thumb_link"]}}" />
                @empty
                @endforelse
            @endif

i get the error: Invalid argument supplied for foreach() (View: /......../category.blade.php)

but when i do:

            @if(! empty($category->categoryGallery))
                @forelse ($category->categoryGallery as $image)
                    <img src="{{$image["thumb_link"]}}" />
                @empty
                @endforelse
            @endif

it works.

Why doesn't the forelse works as it should?

Bart

27 Oct
2 years ago
17 Oct
2 years ago

BartHuis started a new conversation Debug Toolbar Vs Blackfire For Performance Testing?

Hi, when you want to do a performance test on your laravel app, the debug toolbar from barry will slow down it itself i understood. What's your experience with blackfire on windows/homestead/vagrant? (https://laravel.com/docs/5.0/homestead#blackfire-profiler) and on a live real linux server? What would you recommend? Bart

14 Oct
2 years ago

BartHuis left a reply on How To Make Your Own Artisan Functions?

sorry, didn't answer, found it allready from @tomi , but thanks.

for others who want a clear:all function in artisan:

php artisan make:command ClearAll

and put this code in ClearAll.php:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class Clearall extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'clear:all';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Perform all clear functions of other artisan commands: cache:clear, config:clear, debugbar:clear, route:clear, view:clear';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $this->call('cache:clear');
        $this->call('config:clear');
        $this->call('debugbar:clear');
        $this->call('route:clear');
        $this->call('view:clear');

    }
}

BartHuis left a reply on Homestead And Subdomains

the solution of @domandtom worked for me, if you have an other subdomain not working on windows with homestead/vagrant: log into your vagrant (vagrant ssh)

cd /etc/nginx/sites-available/
ls

here are the files to edit for your domains, look up your domain, for example devdomain.dev, and then edit that one:

sudo vim devdomain.dev

look for the line where your domain is, in this example devdomain.dev:

server_name devdomain.dev;

and add the * domain to the same row like this:

server_name devdomain.dev *.devdomain.dev;
12 Oct
2 years ago

BartHuis started a new conversation How To Make Your Own Artisan Functions?

Hi,

How can you make your own artisan functions?

We would like to make one command:

artisan clearall

and let that one trigger:

artisan cache:clear
artisan view:clear
artisan route:clear

Is there a way to make such command ourselves?

Bart

BartHuis started a new conversation Make Api.domain.ext The Stateless Passport Route And Change .ext/api To Normal Route

Hi,

I installed passport, and I got the API functionality working with 2 environments, one getting the data from an other by a Personal Access Token in the get header. Great functionality.

But now i want to change some things. I changed the basic api routing so that api.domain.ext becomes the real api with oauth protection, and domain.ext/api is callable by your browser with the session driver, so without a token in the header for testing purposes. But i think i'm missing a part where the choice is what routes needs to be protected by what guard.

I did set it in config/auth.php:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],

        'browserapi' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

and in the Providers/RouteServiceProvider.php file:


    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {

        $this->mapBrowserApiRoutes();

        $this->mapApiRoutes();

        $this->mapWebRoutes();



        //
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::group([
            'middleware' => 'web',
            'namespace' => $this->namespace,
        ], function ($router) {
            require base_path('routes/web.php');
        });
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapBrowserApiRoutes()
    {
        Route::group([
            'namespace' => $this->namespace,
            'prefix' => 'api',
        ], function ($router) {
            require base_path('routes/browserapi.php');
        });
    }

    /**
     * Define the "browser api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::group([
            'domain' => 'api.{domain}.{ext}',
            'namespace' => $this->namespace,
        ], function ($router) {
            require base_path('routes/api.php');
        });
    }

where can i set to use the api guard on the subdomain and browserapi on the /api prefix?

Bart

30 Sep
2 years ago

BartHuis left a reply on Variable In Router To Define Namespace

and how would you pass that to namespace? or could i just do:

Route::group([ 'namespace' => env('APP_TYPE')], function() {
  // routes...
});

this?

BartHuis started a new conversation Variable In Router To Define Namespace

Hi, in the router i could do:

    Route::group('namespace' => 'Admin'], function() {
        // Controllers Within The "App\Http\Controllers\Admin" Namespace
    });

so i guess this would work too:

    Route::group(['prefix' => '/admin','namespace' => 'Admin'], function() {
        // Controllers Within The "App\Http\Controllers\Admin" Namespace
    });

But what if i would like to let a variable define my namespace?

We have an .env file with some rows that overrules the config/app.php settings like:

APP_ENV="local"
APP_KEY=base64:xxx=
APP_DEBUG=true
APP_LOG_LEVEL="debug"
APP_URL="http://localhost"
APP_NAME=xxappname
APP_TYPE=xxapptype

now i would like to do something like this:

Route::group(['configvar' => '{apptype}','namespace' => $apptype], function() {
        // Controllers Within The "App\Http\Controllers\Apptype" Namespace
    });

just like how you can pass url vars to the router. Is this possible in some way?

Thanks, Bart

27 Sep
2 years ago

BartHuis left a reply on Using Nestedset In Model To Get Tree

Thanks, i'll try something :D

BartHuis left a reply on Using Nestedset In Model To Get Tree

@lazychaser thanks for passing by. i thought that when you make a function in the model with that name, you can use it as an relation? if not, how would you get the features connected to the ancestors categories?

BartHuis left a reply on Using Nestedset In Model To Get Tree

ps: in my controller i have the function that's attached to my router:

public function categoryWithParentFeatures{ $category = \App\Category::whereTranslation('path', $catSlug)->with('products')->with('allCategoryFeatures')->firstOrFail();

    return view('category', ['category'=>$category]);

}

BartHuis left a reply on Using Nestedset In Model To Get Tree

nope, same error, same output from print

BartHuis started a new conversation Using Nestedset In Model To Get Tree

Hi, We're using the lazychaser/laravel-nestedset (on gidhub) / Kalnoy\Nestedset (composer/packagist) package. The seeder is working. But when i want to get the tree by a function in my model, it gives errors that are untraceable for me:

(deleted parts not needed for problem solving)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Kalnoy\Nestedset\NodeTrait;


/**
 * Class Category
 */
class Category extends Model
{
    use \Dimsav\Translatable\Translatable;
    use NodeTrait;

    protected   $fillable = [
        'visible'
    ];

    /**
     * Get the product records associated with the category.
     */
    public function products()
    {
        return $this->hasMany('App\Product');
    }
   
    /**
     * Get the category feature records associated with the category.
     */
    public function categoryFeatures()
    {
        return $this->hasMany('App\CategoryFeature');
    }

    /**
     * Get the category feature records associated with the category.
     */
    public function allCategoryFeatures()
    {
        // when visiting the url where i'm 3 levels deep, i'm getting the right category, but as you see:
        print_r($this->isRoot());  // returns: 1       
        print_r($this->ancestors()->get()->toTree()); // returns: Kalnoy\Nestedset\Collection Object ( [items:protected] => Array ( ) )
        // it doesn't seem to recognise the nestedset system

        $ancestors         = ($this->isRoot()) ? NULL : $this->ancestors()->get();

        $categoryCollection   = (empty($ancestors)) ? $this->with('categoryFeatures') : $ancestors->toTree()->with('categoryFeatures');

        return $categoryCollection;
    }
///////////
// etc
//////////
}

As you can see in the comments in the code it doesn't seem to get the nestedset system...

In the end i'm getting:

BadMethodCallException in Builder.php line 2437:
Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()
1. in Builder.php line 2437
2. at Builder->__call('addEagerConstraints', array(array(object(Category))))
3. at call_user_func_array(array(object(Builder), 'addEagerConstraints'), array(array(object(Category)))) in Builder.php line 1433
4. at Builder->__call('addEagerConstraints', array(array(object(Category)))) in Builder.php line 655
5. at Builder->loadRelation(array(object(Category)), 'allCategoryFeatures', object(Closure)) in Builder.php line 633
6. at Builder->eagerLoadRelations(array(object(Category))) in Builder.php line 324
........................
etc
........................

can't $this be accessed in the model or something? do you have any ideas on how to get this working?

Bart

20 Sep
2 years ago

BartHuis started a new conversation Using Middleware To Handle Url Formatting, No User Access Checking

Hi, All cases i find about middleware explain it through users, user roles, permissions etc. Does anyone knows an example on how to use middleware only to break down an url into variabls and pass that through to the function called?

For example, if you have:

Route::get('foo/{param1}/{param2}/thing-{thing1}/thing-{thing2}', ['uses'=>'[email protected]']);
Route::get('bar/{param1}/{param2}/thing-{thing1}/thing-{thing2}', ['uses'=>'[email protected]']);

You can make the functions in the two controllers:

FooController:

public function fooByParamAndThings($param1,$param2,$thing1,$thing2){
        if($param1 = something){
                $params  = $param1.$param2;
        }
        if($thing1= somethingelse){
                $things = $thing1.$thing2;
        }

        $foo= \App\Foo::where('param', $param)->where('thing', $thing)->firstOrFail();

        return view('foo', ['foo'=>$foo]);
    }

BarController:

public function barByParamAndThings($param1,$param2,$thing1,$thing2){
        if($param1 = something){
                $params  = $param1.$param2;
        }
        if($thing1= somethingelse){
                $things = $thing1.$thing2;
        }

        $bar= \App\Bar::where('param', $param)->where('thing', $thing)->firstOrFail();

        return view('bar', ['bar'=>$bar]);
    }

This should work.

But:

Wouldn't it be much better to use a ParamThings middleware that performs all the actions on the params and things, and only passes the results to the functions? now the actions on that params and things are duplicate in the code.

But how to get the url variables to the middleware, and how to pass the $params and $things to the function?

Bart

BartHuis left a reply on Multiple View Composers

@NikRadadiya and what if you want multiple you do this?

View::composer(
     [ 'profile' , 'user'] , 'App\Http\ViewComposers\ProfileComposer'
);
View::composer(
    [ 'dashboard' , 'overview'] , 'App\Http\ViewComposers\DashboardComposer'
);
19 Sep
2 years ago

BartHuis started a new conversation Generate Route For Multiple Variables/that/has/to/be/passed/to/the/router

hi,

I have a router file:

//multiple router lines before, at the end everything else has to be handled:
Route::get('/{slug}', ['uses'=>'[email protected]'])->where('slug ', '(.*)'); // or return not found
//the route beneath don't has to be triggered, as all routes would match the above
Route::get('/{categoryname}/{categorysubname}/{filter}', ['uses'=>'[email protected]']); // or return not found

when i'm going to domain.dev/categoryname it's working.

But when i go to domain.dev/categoryname/categorysubname, categoryBySubNameView is triggered, instead of passing "categoryname/categorysubname" as the slug to the categoryByCategoryslugView. I thought the where('slug ', '(.*)') part should do the trick, but it doesn't.

Yes, i know i can pass multiple variables to the function in the controller, but theres a certain reason why i want to pass the whole slug to the function. how could i do that?

Bart

08 Sep
2 years ago

BartHuis started a new conversation Multiple View Composers

hi,

In the docs is an example of view composers (https://laravel.com/docs/5.3/views#view-composers). And how to make the composer service provider:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        // Using class based composers...
        View::composer(
            'profile', 'App\Http\ViewComposers\ProfileComposer'
        );

        // Using Closure based composers...
        View::composer('dashboard', function ($view) {
            //
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

and then there's a part on how to use multiple views:

Attaching A Composer To Multiple Views

You may attach a view composer to multiple views at once by passing an array of views as the first argument to the composer method:

View::composer(
    ['profile', 'dashboard'],
    'App\Http\ViewComposers\MyViewComposer'
);

but what if i want to attach multiple composers to different views? normally you put each list in an array by adding [ ] around it, but if i would do that now, it would be something like this? looks strange to me:

View::composer(
    [
        ['profile' , 'App\Http\ViewComposers\ProfileComposer'],
        [ 'dashboard' , 'App\Http\ViewComposers\DashboardComposer']
    ]
);

and if you would like to use multiple views on multiple composers? something like this?

View::composer(
    [
        [ [ 'profile' , 'user'] , 'App\Http\ViewComposers\ProfileComposer'],
        [ [ 'dashboard' , 'overview'] , 'App\Http\ViewComposers\DashboardComposer']
    ]
);

it looks not good to me, and its not in de docs...

Bart

BartHuis left a reply on Caching Eloquent Models Since Laravel 5

True :)

We'll look at our core project first, and how its performing without cache. when we do need cache, i think we'll dive deeper into the possibilities, and maybe we can make a combination on russian doll and yours.

07 Sep
2 years ago

BartHuis left a reply on Article: The Art Of Using Repositories In Laravel 5.3

thanks, we'll talk about my specific implementation on the other topic ;)

BartHuis left a reply on Caching Eloquent Models Since Laravel 5

@Omranic that sounds good.

i have two other concerns here:

  • Why isn't this possible out of the box with laravel. I should think automatisch cache without defining your keys should be one of the core functions of a cache system?
  • When you build an larger application, you would like to cache nested items. For example: I have categories with products. I have a request for a specific selection of catagories with products. The products must be cached, the categories with the products are cached, and the selection is cached. When you update one product, that cache has to be removed, the parent categorie cache had to be removed, and the selection cache has to be removed, but when requesting the selection again, alle categories without changed products can be get from the cache and all products that are not changed in the changed category, can be got from the cache. only the changed product can be taken from the db again, put into cache, and the category can be cached again with all the other allready cached products, and the selection can be cached again with all the other allready cached categories. The so called "russian doll caching", cache nested items. @JeffreyWay allready made video series on that: https://laracasts.com/series/russian-doll-caching-in-laravel only that's based on views, he was planning to make an extra video on applying the idea on models, reminded him today on twitter if he would look at that. Maybe there are better way's to do it since the last video's on that topic...

BartHuis left a reply on Caching Eloquent Models Since Laravel 5

The only thing what I think of now, is that I think that the package of @Omranic doesn't handle deletion of cache when updating, bezause you give a time limit.... you'll need something like the russion doll caching from the video here at laracast, but there's no update on that one for models, it only worked with views...

BartHuis left a reply on Caching Eloquent Models Since Laravel 5

ah, just looked at that function, but there you still have to give your own cache tags. that's just the thing we dont want.

  • i have a table products with 20 products.
  • a user performs a search and 15 products will be shown.
  • a second user performs the same search, we want it to be cached, so no new database query
  • we update one product
  • the cache where that products are in, have to be deleted
  • a third user performs the same search as the first 2 persons, then it will build the new cache

the @Omranic way would cache it including the options given (where, offset, limit etc).

BartHuis left a reply on Caching Eloquent Models Since Laravel 5

but wasn't the remember function removed from 5 and up?