Marwelln

Marwelln

Member Since 5 Years Ago

Experience Points
19,000
Total
Experience

1,000 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
79
Lessons
Completed
Best Reply Awards
13
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.

Level 4
19,000 XP
24 Feb
4 years ago

Marwelln left a reply on Trim All Input

This might work for you. Haven't tested it.

class Model extends \Illuminate\Database\Eloquent\Model {
    
    public static function boot() {
        parent::boot();

        static::saving(function($model){
            $model->forceFill(array_map('trim', $model->getAttributes()));
        });
    }
    
}

Trim will in this case run on all the attributes the model has and then refill it to the model before saving it.

14 Feb
4 years ago

Marwelln left a reply on Outputting A String Inside HTML Tag Produces ""string""

" will be escaped, so you need to use {!! !!}.

<li {!! Request::is('store', 'store/*') ? 'class="active"' : null !!}>
    <a href="#">Store</a>
</li>

{{ }} will give you <li class=&quote;active&quote;>.

13 Feb
4 years ago

Marwelln left a reply on Expanding Dd() (VarDumper) By Default?

I would like this too. It's really time consuming to have to expand a level manually when it can be displayed without problems.

04 Feb
4 years ago

Marwelln left a reply on Order By Eloquent

Try this:

Product::with(['images', 'comments.owner' => function($query) {
    return $query->orderBy('created_at', 'asc');
}])->findOrFail();
01 Feb
4 years ago

Marwelln left a reply on Why Is This Returning Trying To Get Property Of Non-object?

Must likely because $this->items is false and you return null. You can't access a property from a null value.

Same with your query. If first() doesn't get any hits, it will return null.

06 Dec
4 years ago

Marwelln started a new conversation [Package] Recaptcha - Googles New (december 2014) 1 Click Recaptcha

Github

What is reCAPTCHA?

reCAPTCHA is a free service to protect your website from spam and abuse. reCAPTCHA uses an advanced risk analysis engine and adaptive CAPTCHAs to keep automated software from engaging in abusive activities on your site. It does this while letting your valid users pass through with ease.

This package gives you an easy validation in PHP for Google's new (december 2014) reCAPTCHA. It allows you to validate if you are a human or robot with just a simple mouse click. See this Youtube link for a brief look at how it works.

Installation

You can install this package by using Composer.

  • Option 1: Add "marwelln/recaptcha" : "dev-master" to your composer.json file and run composer update.
  • Option 2: Run composer require marwelln/recaptcha:dev-master

Laravel

If you're using Laravel, you need to 'Marwelln\Recaptcha\RecaptchaServiceProvider' to your providers array in config/app.php.

Recaptcha keys

To use reCAPTCHA, you need to have a site key and a secret key. Click here to setup a domain and get your keys.

The site key is using for the widget and the secret key is used to validate the response we get from Google.

Front-end usage

To display the reCAPTCHA widget, you first need to include their javascript file on your site. Put the following code at the bottom of your site.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

After that, you need to add a div where you want to display the widget. The required attributes is class with a value of g-recaptcha and data-sitekey with a value of your site key. Don't have a key? Get one over here.

<div class="g-recaptcha" data-sitekey="your_site_key"></div>

There are three optional attributes available for you to style and manage the widget. It's data-theme, data-type and data-callback. See Google's configuration documentation for up-to-date and more details about each attribute.

Laravel

If your using Laravel, you can display the widget by including the available view file. This will include the script file and the div tag.

Laravel 4:

{{ View::make('recaptcha::display') }}

Laravel 5:

{!! View::make('recaptcha::display') !!}

Back-end usage

To validate the response we get from Google we use the Marwelln\Recaptcha\Model class.

$validator = new \Marwelln\Recaptcha\Model($_POST['g-recaptcha-response'], $secretKey);
$validated = $validator->validate();

$response = '';
if ( ! $validated) {
    $response .= '<pre>' . print_r($validator->errors(), true) . '</pre>';
}

$response .= 'Did I validate? ' . ($validated ? 'Yes.' : 'No.');

echo $response;

If you don't want to insert $secretKey everytime you want to validate the response, you can add an environment value with RECAPTCHA_SECRETKEY as key.

putenv('RECAPTCHA_SECRETKEY=my-recaptcha-secret-key');

$validator = new \Marwelln\Recaptcha\Model($_POST['g-recaptcha-response']);

Laravel

Laravel validation is supported by using the recaptcha validation rule on g-recaptcha-response.

$rules = [
    'g-recaptcha-response' => 'required|recaptcha'
];

$validator = Validator::make(Input::all(), $rules);
$validated = $validator->passes();

$response = '';
if ( ! $validated) {
    $response .= '<pre>' . print_r($validator->errors()->all(), true) . '</pre>';
}

$response .= 'Did I validate? ' . ($validated ? 'Yes.' : 'No.');

return $response;

Errors

If validate() fails, you can get the errors by calling $validator->errors(). This will return an array with codes errors keys. See Error code reference at the documenation website.

If you are using Laravel, errors() will return an instance of Illuminate\Support\MessageBag with all errors translated.

Laravel configuration

There is not really a need to publish the configuration file. Both the siteKey and secretKey should be set in your environment file so it won't be available in your versioning system.

The only option available is to enable or disable curl. So if you're having trouble or don't have access to curl, you can publish the configuration file and change the curl value to false. We will then use file_get_contents instead.

Laravel 4:

php artisan config:publish marwelln/recaptcha

Laravel 5:

php artisan publish:config marwelln/recaptcha

See Protecting Sensitive Configuration if you don't know how to setup environment variables in Laravel 4.

30 Nov
4 years ago

Marwelln left a reply on Laravel 5 - Manual Pagination

Input is available with just the use of use Input;, it's probably the same with Paginator, use Paginator; instead of use Illuminate\...\Paginator.

Marwelln left a reply on Laravel 5 - Manual Pagination

Try with this in your products method:

public function products(Paginator $paginator)
{
    $products = [];
    return $paginator->make($products, count($products), Input::get('limit') ?: '10');
}
25 Nov
4 years ago

Marwelln left a reply on Example On How To Use Multiple Locales In Your Laravel 5 Website

@rsdev000, you can translate your routes by using the trans helper in your routes.php.

22 Nov
4 years ago

Marwelln left a reply on View Share - Breaking Migrations

Why don't you just use Auth::user()? It does exactly what you have done and $currentuser->profile is still accessible.

If there are no user logged in, it will be null, otherwise it will be an instance of your user model.

View::share('currentuser', Auth::check() ? Auth::user() : null);

Marwelln started a new conversation Example On How To Use Multiple Locales In Your Laravel 5 Website

The following will make domain.com/{locale} available to your website.

What you need to use multiple locales is three things.

  1. Add list of available locales to an array.
  2. Prefix all your routes with current locale.
  3. A language middleware that checks if user is using a valid locale.

Step 1: Add your locales

Open up config/app.php and add the following below 'locale' => 'xx'.

'locales' => ['en' => 'English', 'sv' => 'Swedish'],

Modify this array with your desired locales.

Example at Github

Step 2: Prefix your routes

To prefix our routes, we change the map method in app/Providers/RouteServiceProvider.php. Change the map method to the following:

public function map(Router $router, Request $request)
{
    $locale = $request->segment(1);
    $this->app->setLocale($locale);

    $router->group(['namespace' => $this->namespace, 'prefix' => $locale], function($router) {
        require app_path('Http/routes.php');
    });
}

Then add this to the top of the file:

use Illuminate\Routing\Router;
use Illuminate\Http\Request;

Example at Github

Step 3: Create a language middleware

Now create a file named Language.php in app/Http/Middleware with this content:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Redirector;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Routing\Middleware;

class Language implements Middleware {

    public function __construct(Application $app, Redirector $redirector, Request $request) {
        $this->app = $app;
        $this->redirector = $redirector;
        $this->request = $request;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Make sure current locale exists.
        $locale = $request->segment(1);

        if ( ! array_key_exists($locale, $this->app->config->get('app.locales'))) {
            $segments = $request->segments();
            $segments[0] = $this->app->config->get('app.fallback_locale');

            return $this->redirector->to(implode('/', $segments));
        }

        $this->app->setLocale($locale);

        return $next($request);
    }

}

Example at Github

Now make that middleware run on all requests by adding it to the $middleware property in app/Http/Kernel.php. It is recommended to add it to the top of the array.

protected $middleware = [
    'App\Http\Middleware\Language',
    'Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode',
    'Illuminate\Cookie\Middleware\EncryptCookies',
    'Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse',
    'Illuminate\Session\Middleware\StartSession',
    'Illuminate\View\Middleware\ShareErrorsFromSession',
    'Illuminate\Foundation\Http\Middleware\VerifyCsrfToken',
];

Example at Github

You are now set to go.

Example repo

I have an example repository available at https://github.com/Marwelln/laravel-multiple-locales – clone it to test it out or if you are unsure how it works.

13 Nov
4 years ago

Marwelln left a reply on Dumb Question: How Do I Link To To My CSS File ?

There is no built in compiler/compressor, so if you want it inside app/assets, use Elixir or Basset. Both can compile and compress your assets to the public directory.

Marwelln left a reply on Laravel 4 Routes Namespace Like Laravel 5

Group them, just like in 5.

In L5:

$router->group(['namespace' => 'App\Http\Controllers'], function($router) {
    require app_path('Http/routes.php');
});

So in L4, use this (in your routes.php):

Route::group(['namespace' => 'App\Http\Controllers', function() {
    // Your routes here.
});
11 Nov
4 years ago

Marwelln left a reply on Exception Handling In Laravel 5.0

Or is it? How do you try to access it? It should be available with Session::get('msg').

10 Nov
4 years ago

Marwelln left a reply on A Few Elloquent Wheres

Don't really get what you want to do, but it seems like it's scopes your looking for.

public function scopeSomething($query)
{
    return $query->where('votes', '>', 100);
}

If it's initializing your query you're having problem with, use newQuery.

$propertiesDb = Property::newQuery();

Marwelln left a reply on Using Non-Laravel Composer Package With Laravel

It's PHP. Laravel is built on PHP. Just read the docs and get started.

Marwelln left a reply on Laravel 5 Validation (FormRequest)

It redirects you back to the previous page as defaults or returns a json response if you're using ajax.

public function response(array $errors) 
   {
        if ($this->ajax())
       {
            return new JsonResponse($errors, 422);
       }
       return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors);
}

You can override the response method in app/Http/Requests/Request.php to "have it your way".

08 Nov
4 years ago

Marwelln left a reply on Problems When Uploading Site To Production Server

class is a reserver word in PHP 5.4. You should rename the method / constant to something else.

06 Nov
4 years ago

Marwelln left a reply on A Good Captcha Package

I've used greggilbert/recaptcha a lot of times. It's a solid pick.

Marwelln left a reply on Where Do You Set The Public Directory In Laravel 5?

Thanks mate. I added it to AppServiceProvider.php.

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {

    ...

    public function register()
    {
        $this->app->bind('path.public', function() {
          return base_path().'/public_html';
        });
    }

}

Marwelln started a new conversation Where Do You Set The Public Directory In Laravel 5?

I have my public directory named public_html instead of public. So where do I change this setting?

I have a packages that uses $this->app['path.public'], but that package is trying to use public instead of what I want, public_html. So how do I tell Laravel 5 to use public_html?

05 Nov
4 years ago

Marwelln left a reply on Elixir On 4.2

It is possible to use it outside of Laravel 5 (except for events, routes and phpunit). In my app I have my assets in app/assets and public_html instead of public. This is my gulpfile.js:

var elixir = require('laravel-elixir');

elixir.config.assetsDir = 'app/assets/';
elixir.config.cssOutput = 'public_html/css';

elixir(function(mix){
    mix.less('app.less')
           .version(['css/app.css', 'public_html/build']);
});

One thing you have to change manually (if you're not using public) is to change

return gulp.src(src, { base: './public' })

to

return gulp.src(src, { base: './public_html' })

in node_modeules\laravel-elixir\ingredients\version.js.

03 Nov
4 years ago

Marwelln left a reply on New Home Page

Adding background-size:cover wouldn't hurt for those with large browser width. Image looks just fine with it.

@media (min-width:1700px) {
    .home-banner { background-size:cover; }
}
02 Nov
4 years ago
01 Nov
4 years ago

Marwelln left a reply on ClassNotFoundException

Because you are using namespaces, every time you want to access that model you either need to have use App\Profile; at the top of your file or include the full namespace App\Profile::find(x).

31 Oct
4 years ago

Marwelln left a reply on Passing User Object To Views

You can create a new file in app/ named views.php and then require it at the bottom in app/start/global.php.

Marwelln left a reply on Passing User Object To Views

You can use View::share or View::composer.

share (set variable to all view files)

View::share('user', Auth::user());

composer (will set variable to all view files thanks to the wildcard *)

View::composer('*', function($view){
    $view->with('user', Auth::user());
});

Marwelln left a reply on How About An Episode On Ardent ?

The validator class still exists if you're not using a a http request.

Marwelln left a reply on How I Can Try AND In Laravel Query Builder ?

Just append a new where(...) to your query. It will autmatically be AND.

Table::where('Column', Value)->where('NewColumn', Value)->get();

More details are available in the docs here.

30 Oct
4 years ago

Marwelln left a reply on Dumping Objects

You need to use the with method in your query if you want it to display when you dump it. This is called Eager loading.

$foobar = Model::with('image')->where('id', 1)->get();
29 Oct
4 years ago

Marwelln left a reply on Updating Laravel 5?

git remote add upstream https://github.com/laravel/laravel.git
git fetch --all
git merge upstream/develop

if you are developing in the same repo, you'll have to fix some conflicts from time to time, but if you do it every day it gets easier

Then every time you want to merge again, you run git fetch --all followed by git merge upstream/develop.

28 Oct
4 years ago

Marwelln left a reply on [L4] Where Does Laravel Store The Last Migration Batch It Ran?

Add the name of the file (exluding the extension) to the table migrations in your database to "trick" Laravel that it's already been run.

Marwelln left a reply on [L5] Create Custom Validators

You can create custom validators in your FormRequest class by setting app('validator') to your validator property, and then run extend on that.

public function __construct() {
    $this->validator = app('validator');

    $this->validator->extend('foobar', function($attribute, $value, $parameters) {
       return ! Model::where('foobar', $value)->exists();
    });
}

In my rules I have this:

public function rules() {
    return [
        'id' => ['required', 'foobar']
    ];
}

If you don't want to clutter your construct you can to it like this:

public function __construct() {
    $this->validator = app('validator');

    $this->validateFoobar($this->validator);
}

And then the method:

public function validateFoobar($validator) {
    $validator->extend('foobar', function($attribute, $value, $parameters) {
        return ! Model::where('foobar', $value)->exists();
    });
}
27 Oct
4 years ago

Marwelln left a reply on Quick Question On L5 Route Annotations

As far as I know you need to use elixir to automatically update your routes if you are using annotations.

Marwelln left a reply on L5 Validation Not Picking Up Custom Messages

It's most likely because your are using Camel Case. Try with not_in instead.

26 Oct
4 years ago

Marwelln left a reply on Break, Continue, Return In Blade Template

Usually you wouldn't need to, but if you must, use <?php return; ?>

25 Oct
4 years ago

Marwelln started a new conversation Post Count Style Failing

Post count are in their own line if browser width is too small. Without display:flex.

I suggest you to discard your usage on float and use display:flex; instead. With display:flex.

  1. Add display:flex; and justify-content:space-between to .media--conversation.
  2. Remove float:left; from .media--conversation__avatar.
  3. Remove float:left; and add flex-grow:2; on .media--conversation__body.
  4. Remove float:left; from .media--conversation__meta.

... or fix it your own way. :-)

24 Oct
4 years ago

Marwelln left a reply on Controller Class Not Found

@Everon, change $this->rootUrlNamespace to your actual namespace.

$router->group(['namespace' => 'App\Http\Controllers'], function($router) {
    require app_path('Http/routes.php');
});

I really hope this get added as default, otherwise you would have to add this for every new Laravel project, which would be stupid.

Marwelln left a reply on Eloquent Create Method - Always Inserts Blank Entries.

Show us a dump of your $data and your $fillable property in your model.

Marwelln left a reply on Working With Files Best Practices.

Setup Model events.

This is what I have in my Image model:

public static function boot() {
    parent::boot();

    // Delete the image from the filesystem after deleting our database entry.
    static::deleted(function($model){
        (new Filesystem)->delete($model->systemPath);
    });
}

So whenever I do Image::find($id)->delete() the deleted event will fire and remove the image from my file system.

23 Oct
4 years ago

Marwelln left a reply on DB::Select To Eloquent

See my update.

Marwelln left a reply on DB::Select To Eloquent

Try this (not tested, just from guess):

$locations = InvLocation::whereNotIn('id', function($query) use ($id) {
    $query->table = 'inv_devices';
    $query->select(['location_id']); 
    $query->where('item_id', $id); 
})->get();
19 Oct
4 years ago

Marwelln left a reply on Upgrading To Php 5.6 On Vagrant

What operating system are you using?

Marwelln left a reply on Elixir Rev-manifest Windows Issues

@lytedev, sindresorhus made modifications to my commit making it return a full path instead of a relative.

Go into node_modules/gulp-rev aand open up index.js and change the relPath function to this:

function relPath(base, filePath) {
     if (filePath.indexOf(base) !== 0) {
        return filePath.replace(/\\/g, '/');
    }
    var newPath = filePath.substr(base.length).replace(/\\/g, '/');
    if (newPath[0] === '/') {
        return newPath.substr(1);
    } else {
        return newPath;
    }
}
18 Oct
4 years ago

Marwelln left a reply on Elixir Rev-manifest Windows Issues

Update your node packages with npm update. A fix for this have been commited and is available in v2.0.0 of gulp-rev. Elixirs package.json have been updated to include this fix.

16 Oct
4 years ago

Marwelln left a reply on How Do I Gulp Both Css (less) And Javascript?

Thanks mate. Worked wonders.