jusahah87

jusahah87

Member Since 3 Years Ago

Helsinki

Owner at Nollaversio IT

Experience Points 21,870
Experience Level 5

3,130 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 161
Lessons
Completed
Best Reply Awards 23
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.

01 Nov
2 years ago

jusahah87 left a reply on PhantomJS As A Deamon

I don't see why not.

But maybe it'd be easier to have daemon process which launches separate PhantomJS processes, one per HTML file. Each PhantomJS process reads the file, renders the HTML, takes screenshots, saves it to the disk, and exists.

This way your daemon process can simply focus on listening for file events (modify, create).

jusahah87 left a reply on Real Singleton?

@UAVova

This is a deep subject.

You are thinking of singleton in terms of how singleton works in Node.js script or similar. In typical Node.js script, a singleton object could literally be shared by many users.

In PHP, there is no such thing as shared by many users. Only way to share data between two users is to use database or similar external service. In PHP, all variables instantiated during script run are alive only during the script run. After the HTTP response is sent back, your PHP script simply dies and your variables - singletons or not - die with it.

jusahah87 left a reply on Real Singleton?

@UAVova You are fundamentally misunderstanding how PHP works in request-response architecture.

PHP script does not retain state between two requests (page refreshes). Each page refresh starts PHP script from scratch.

jusahah87 left a reply on Tutorial Is Wrong?

@UAVova Where in the tutorial? What time?

jusahah87 left a reply on Tutorial Is Wrong?

That possibly could not work - you are trying to inject function call (dd) as variable type of the first formal parameter ($stat).

jusahah87 left a reply on How To Handle General Page Navigation

I would have one controller - like StaticPagesController - for all static public pages.

The point is that these pages like about, contact, faq are static so there is very little functionality inside controller methods. Having separate controller for each page simply clutters your app.

Model-related routes are logically divided into multiple controllers - CarController, GarageController, etc.

jusahah87 left a reply on Can Create Model Name As Model And Table Name As Models

Well, rename it to something else?

Like ProductModel or something. You can still keep the table name.

31 Oct
2 years ago

jusahah87 left a reply on Layout Variables

Oh frag, I totally forgot Laravel 5.3 messed up Controller constructors. Well, maybe you could inject Request and access user from there?


use Illuminate\Http\Request;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

   public function __construct(Request $request)
    {
        $this->middleware('auth');

        view()->share('user', $request->user());

    }

}

jusahah87 left a reply on Layout Variables

Yeah, you can pass either globally (to all views) or controller-namespaced (to all views within one controller):

Global - check here: https://laravel.com/docs/5.3/views#sharing-data-with-all-views

Controller-spaced:


class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

   public function __construct()
    {
        $this->middleware('auth');

        $this->user = Auth::user();

    view()->share('user', $this->user);
    // Now you have $user variable present in all views
        // generated from here or sub-classes.
    }

     public function logout() 
    {
        Auth::logout();
        
        return redirect('admin/dealer');
        
    }
}

jusahah87 left a reply on AJAX Operation Doesn't Work

@yeshwanthvshenoy It still gives the error because of the exact reason you mentioned - it is not a form. Therefore adding csrf_field above the button does nothing.

You must do two things to achieve csrf_token protection with Ajax:

  1. Add meta field to your document.

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

  1. Make sure jQuery includes crsf_token when doing the request

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Refer here for more info: https://laravel.com/docs/5.3/csrf

jusahah87 left a reply on Users, Groups, Permissions

I would do it by collapsing all settings into one column, and saving JSON string. This gives most flexibility for future too.

Jeffrey has a video about this: https://laracasts.com/lessons/managing-mass-user-settings

jusahah87 left a reply on Guidelines For Calling External API's

@roemer Yeah, that sounds fine.

You could also just register a custom Artisan Command and have a cron job to execute it once a night. Then all you integration code would be nicely stashed inside a Command class.

https://laravel.com/docs/5.3/artisan

jusahah87 left a reply on What Is The Best Practice To Create A Custom Function Laravel?

Well, just make a global normal PHP function. That function can then call other services (Eloquent model methods, etc.) as it wants. It is all encapsulated into that one global function.

jusahah87 left a reply on Guidelines For Calling External API's

Service Provider makes sense to me. It is a service after all. Service that calls external API once a day.

jusahah87 left a reply on AJAX Operation Doesn't Work

It baffles me how so many devs don't know how to inspect responses to AJAX calls. Have you not heard of Chrome Dev Tools or similar...?

Check the response status of the ajax call and start from there.

30 Oct
2 years ago

jusahah87 left a reply on Merge Two Table ( Join Them Together ) As One Model File

There is always a way. You could have three Eloquent models:

User

FacebookUser

NormalUser

User-model is polymorphic model, and its table simple contains three columns: id, concrete_id snd concrete_type.

FacebookUser and NormalUser are normal Eloquent models with their own table schemas.

Then you simply override User model's newFromBuilder method so that it does one additional fetch to either facebook table or normal user table, depending on the concrete_type.

jusahah87 left a reply on Selecting From Existing And Adding A New Record As Well

POST request comes in with data something like this:


[
    'name' => 'Les Miserables',
    'year' => 1881,
    'authors': [
        1, // existing author id
        2, // existing author id
        [
            'name' => 'John Gray', // new author
        ]
    ]
]

Controller is smth like:


public function saveBook(BookCreationRequest $request) {

  //Form request BookCreationRequest validated input values
  
  $authorIDs = $request->input('authors')->map(function($authorData) {
      if (is_array($authorData)) {
          // New author data, save to DB
          $author = new Author($authorData);
          $author->save();
          return $author->id;
      }
      // Existing author, fetch from DB
      // By fetching from DB we ensure the given ID is valid
      return Author::findOrFail($authorData)->id; 
  });

  // Create and save book
  $book = Book::create([
    'name' => $request->input('name');
    'year' => $request->input('year');
  ]);
  $book->save();

  // Associate the authors with the book
  $book->authors()->attach($authorIDs);

}

You could wrap whole thing / part of the thing inside DB transaction if needed.
29 Oct
2 years ago

jusahah87 left a reply on Loading Tags With Select2 And Ajax

Should be easy to debug.

  1. Does ajax ever hit the server-side? Run the javascript example with Chrome Dev Tools's network tab open.
  2. If yes, what does the $request->tag_list actually contain?

jusahah87 left a reply on Public Page Is Empty When You Run Laravel

This same thing has happened to me frigging million times. It seems its always a different reason.

  1. Storage directory rights are incorret. Solve by chmod -R 777 the directory.
  2. There is some error out-of-the-box, and error reporting is disabled.
  3. Delete file laravel.log. I dunno why but this has sometimes solved the issue.
  4. Test using php artisan serve. Maybe it works.

jusahah87 left a reply on Coding Is A Bit Boring. Who Agrees?

This is the problem with today's "passion-first" attitude towards work.

I feel like programming is boring 90%, pretty exciting 9%, and super-exciting 1% of the time.

Still hands-down beats out any other realistic career choice I could think of.

jusahah87 left a reply on Missing Argument 2 For App\Permission::scopePermissioneditt()

You have not passing $id in.


$permissions = Permission::permissioneditt($id)->get();

jusahah87 left a reply on How To Hash A Password On Model Static::creating()

Yeah, just use bcrypt helper


$variable->password = bcrypt($request->input('password'));

28 Oct
2 years ago

jusahah87 left a reply on Gradual Loading Of A Page With Laravel?

There is nothing preventing you to do this in PHP per se, but explicitly with Laravel... probably not feasible.

With PHP you can just flush the internal buffers and the TCP connection will push data to the client. However, this does not guarantee that the end user sees the data. The browser may do its own buffering too.

As a general rule, not worth the hassle.

jusahah87 left a reply on Correct Way To Use Config Files

@ricardovigatti That is a valid point. If you need dynamic config values, you should go with the service provider as it provides nice wrapping of the lookup.

And interfaces are crucial here.

jusahah87 left a reply on Relation Eloquent

Well, the getReferrerttribute() should be getReferrerAttribute().

jusahah87 left a reply on Sharing Variables In Seeding

There are many solutions. Put them to the config file and fetch from there. Or even to the environment file. It does not matter as its all for local development anyway.

Then just access them wherever you want like this:


env('var1');
env('var2');
env('var3');

jusahah87 left a reply on Live Search Result

@Tasmin

Well, the basic idea in your code is about right.

Perhaps its some syntax error. Like you seem to miss a opening <script> tag in your footer section. And your server-side code is riddled with simple spelling errors (Reponse)

I would debug this like this:

  1. Find out whether search box callback is actually called when search box content changes.
  2. Find out the status code of the AJAX call (did it fail or succeed?)

jusahah87 left a reply on Form Submitting Query String Parmaters

Seems like POST method is overruled somehow. Probably a problem with Javascript hijacking the form submit.

jusahah87 left a reply on Live Search Result

Yeah, AJAX call is the way to go here. What you are specifically missing here? Your front-end code (Javascript) needs to call back-end route, passing in the search string. Your back-end then queries database and returns results as JSON collection, and the Javascript code pushed the results into the DOM of the page.

This all happens under-the-hood (from the human end-user's point of view). The key point is that a new HTTP request is sent to the back-end every time user changes the string content of the search box, thus allowing the app to display live search results.

jusahah87 left a reply on Querying & Inserting User Specific Data

The accepted answer is technically a correct one, but if you only want to save one single digit (shoe size) per user, I would get rid of the Shoe table altogether. Just put the shoe size into the User table.

If a given User has not submitted his shoe size, the column value is simply NULL.

jusahah87 left a reply on React And Angular 2

@rtorc

If Angular docs jumped from a bridge, would you follow?

I mean no offense, but Angular/React docs are - of course - written by developers who believe in SPA-centric world. Their view is very biased. I am not saying it is a wrong view, but it is definitely a biased one.

jusahah87 left a reply on React And Angular 2

I can answer the last part of your question:

should all web apps now be SPAs

No. God no.

jusahah87 left a reply on Element Changes Save In Separate Table?

A trait is way to go here.


trait Trackable
{
    // This will be called by framework when initializing the app
    public static function bootTrackable()
    {
        static::creating(function ($model) {
            // log
        });

        static::updating(function ($model) {
            // log
        });

        static::deleting(function ($model) {
            // log 
        });
    }
}


class Dog extends Model {
  
  use Trackable;

}

https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Model.php#L317

13 Jun
3 years ago

jusahah87 left a reply on Recursive Loop Not Looping

@lyleyboy One very claring issue is that you are not saving the response of recursive call anywhere. Nor are you passing indendation correctly to inner recursions.

I think you need something like this (I left indendation out for clarity, but you should be able to pass it around):

// Public function, builds the <ul>...</ul>
public static function getHTMLForTreeOfFolders($array) {
   return '<ul>' . static::foldersToHTML(collect($array)) . '</ul>';
}
// Builds the <li> elements
protected static function foldersToHTML ($foldersCollection) {
   return $foldersCollection->reduce(function($carry, $item) {
      $thisItemString = $carry . '<li>' . $item['name'] . '</li>';
      if (isset($item['children'])) {
         return $thisItemString . static::foldersToHTML(collect($item['children']));
      }
      return $thisItemString;
   }, '');
}

10 Jun
3 years ago

jusahah87 left a reply on Slug

How about...


$name = $request->get('name');
$slug = str_slug($name, '-'); // Using Laravel string helper
$news  = new News;
$news->title =$name;
$news->save(); // DB assigns unique id to the model
$news->slug = $slug . $news->id; // Append id to slug to ensure its uniqueness
$news->save(); // Update the model in DB

Because each News model has globally unique ID, this ensures that slug is also globally unique.

07 Jun
3 years ago

jusahah87 left a reply on Knowledge Needed To Make A Live Streaming Functionality

@Eco012390 I would say the first essential piece of knowledge is not to use PHP or Laravel for this.

Perhaps check Node.js with something like webRTC and/or BinaryJS.

Other solution is to go all gloomy on this and use Erlang, C++, etc.

03 Jun
3 years ago

jusahah87 left a reply on Laravel Lazy Eager Loading With Repository

@Viraldope I would say this is on the verge of being unnecessary micro-optimizating.

Both ways are fine, I personally prefer the former one. You are basically decorating the client object with some associated data that the caller expects to be present. As some other routes / callers don't expect that data to be present it is all okay that you do the decoration only inside the index-method.

jusahah87 left a reply on Recive SMS Response?

@lukavic First of all I don't know how Twilio does this. But in Finland we have sms gatewat provider which allows me to send requests for querying whether SMS receiver has answered to his SMS or not.

With that in mind, I would have a scheduled task running every one minute. The task send a query request to SMS gateway for each SMS that was sent from the app. SMS gateway probably provides you with some tracking id when you sent the SMS so you can use that id to query.

When you originally sent the SMS to the customer, you probably want to save this tracking id to some "pending_sms_messages"-table. This way scheduled task can later retrieve all pending messages and ask SMS gateway provider if there is a response from the end-user. If there is a response for the given tracking id, you save the response to database and delete corresponding row from the pending_sms_messages-table.

02 Jun
3 years ago

jusahah87 left a reply on Questioning My Faith In Object Oriented Programming

I can somewhat relate to the sentiment here.

For me OOP - the way most tutorials and guidebooks define it - simply works at too low-level. Like OOP "golden" patterns (encapsulation, polymorphism, composition) are EXCELLENT philosophies, but very often they are applied at wrong level of abstraction (imho).

Like take the debate of whether some method of class should be public or private.

At the detail level you can make a full argument for particular method to be either private of public.

At the higher level it does not matter at all. I mean this quite literally - the "thinking cycles" wasted on these low level micro-considerations represent (to me) a pure waste of time out of learned habit.

So I would say OOP is a great paradigm when applied at the correct level of abstraction. Unfortunately, I think most programming books do not apply at correct level.

I think the correct level of abstraction for OOP is system level. Like how this high-level service component is encapsulated from this other high-level service component. For example, how is this "bulletin board subsystem" properly decoupled from this "banking subsystem". At that level the OOP paradigm (especially SOLID principles) really start to pay off.

I am not saying that OOP should be abandoned at the detail-level when writing individual classes, but that the most cherished OOP principles do not really matter that much at that level. Or lets put it this way: their marginal utility is pretty low.

Should you still use visibility control for class methods? Yeah sure, but don't stress too much about it. Its much more important to get the highest level design right than perfecting all the miniscule details.

30 May
3 years ago

jusahah87 left a reply on Callback Function

@willvincent True. After quick checkup it seems where is part of conceptual inheritance tree but not the actual one. Instead the call is intercepted by a magic method and then rerouted to query Builder.

Pretty nice, Mr. Otwell, pretty nice...

29 May
3 years ago

jusahah87 left a reply on Callback Function

@DarkSpirit It simply works by user's code passing callback function into Eloquent's where method. Inside the callback the query object can be modified ($query->where('user_id', Auth::user()->id)) and then returned. Its just all about decorating (or extending) given database query with additional constraints. When you've finally decorated it enough you do the actual query and get the results.

If you are perhaps wondering why Status.php does not have method called where, its because where lives higher on the inheritance chain. Status extends Model so probably where lives inside Model.php (or even higher up).

One of the key things to note is that here callback function is invoked synchronously. If you have experience with languages like Javascript, well... in Javascript a callback function can be invoked either synchronously or asynchronously. Important to know the difference between these two ways to use a callback function.

jusahah87 left a reply on Post Method Does Not Submit Data To Mysql

@fikri1510 This seems wrong:

{{!Form::open('route'=>'store')!}}

Your named route most probably isn't just "store" - if it is, very poor naming.

Maybe you want something like this...

{{!Form::open('action'=>'[email protected]')!}}

28 May
3 years ago

jusahah87 left a reply on It's Taylor's Birthday Today!

@Harish You are quite right and I - for one - tend to agree with your basic premise. He deserves tons of wishes and love.

jusahah87 left a reply on Making Dynamic Eloquent Scopes

@taijuten Pivot table between Student and Guardian holds all the relevant data for filtering. I would create a separate Model for that table. Here called "StudentGuardian".


// StudentGuardian is pivot model for the many-to-many relation between Students and Guardians.
class StudentGuardian extends Model
{
    // Relations defined to Student and Guardian models not shown

    // Dynamic query builder method
    public function scopeCustomFiltering($query, $filters)
    {
        return $filters->reduce(function($extendedQuery, $filter) {
            return $extendedQuery->where($filter['attribute'], $filter['op'], $filter['val']); 
        }, $query);
    }

}

// example usage
$filters = [
   ['attribute' => 'order', 'op' => '=', 'val' => 1],
   ['attribute' => 'is_legal_guardian', 'op' => '=', 'val' => true]
];
$studentIdsOfSchool = Student::where('school_id', 1)->select('id')->get();
$studentGuardians = StudentGuardian::whereIn('student_id', $studentIdsOfSchool)->customFiltering($filters)->with('guardian')->get();
$guardians = $studentGuardians->pluck('guardian'); // Does pluck work here? Never tried something like this.

jusahah87 left a reply on How To Call A Method Inside Another Method In Laravel 5

@khader Refactor into:


public function gpsdevicereport() {
    $value = session()->get('email');
    return DB::table('gps_device_report')->where('imei_number', '334443')->get();
 }

public function store_test(Request $request){
       
        $imei = $request->get('optImei');
        $date = $request->get('rptDate');
        $user_imei = DB::table('gps_device_report')->where('imei_number', '334443')->get();
        $user_imei2 = $this->gpsdevicereport();
        return view('gps_device_report',compact('user_imei', 'user_imei2'));
    }

The code snippet you gave is truly all over the place. So I don't know, maybe clean it up and explain a bit more...

jusahah87 left a reply on Nested Resources?

@SangminKim Well, at some level it indeed gets a bit if you keep stacking those nested relations like that. I think - as a rule of thumb - that three levels is maximum, after that the code gets too hard to read and reason about.

But do you need Category when accessing a Variation? I think not. Variation is owned by Technology, and thats only thing Variation should care about. Think it like a "Law of Demeter for nested resources".

Route::resource('category', 'CategoryController');
// For accessing tech without category
Route::resource('technology', 'TechnologyController');
// For accessing variation without technology
Route::resource('vartion', 'VariationController');

// For accessing tech through category
Route::resource('category.technology', 'CategoryTechnologyController');
// For accessing variation through technology
Route::resource('technology.variation', 'TechnologyVariationController');

This way you never go more than two levels deep.

jusahah87 left a reply on Nested Resources?

@SangminKim Personally I think there is nothing wrong with having two nouns for one controller.

If Technology is always a member of some one Category, it makes perfect sense to have it as a nested resource. There is a ownership relation between Category and Technology.

Having said that, you could have separate routes for accessing Technology straight.


Route::resource('category', 'CategoryController');
// For accessing tech through category
Route::resource('category.technology', 'CategoryTechnologyController');
// For accessing tech without category
Route::resource('technology', 'TechnologyController');
27 May
3 years ago

jusahah87 left a reply on Get URL For Polymorphic Related Object

What about simply:


class Staff extends Model
{
    /**
     * Get all of the staff member's photos.
     */
    public function photos()
    {
        return $this->morphMany('App\Photo', 'imageable');
    }

   public function getLink() {
      return route('staff.show', ['id' => $this->id]);
   }
}

class Product extends Model
{
    /**
     * Get all of the product's photos.
     */
    public function photos()
    {
        return $this->morphMany('App\Photo', 'imageable');
    }

   public function getLink() {
      return route('product.show', ['id' => $this->id]); 
   }
}
// someview.blade.php
@foreach ($photos as $photo)
   <a href="{{$photo->imageable->getLink()}}">Photo here</a>
@endforeach

jusahah87 left a reply on CRUD: Restrict Access By User Id

@afujita Oh, 4.2 does not have Middleware?

Then I would indeed put it into Controller:

//UserPageController.php

// User is injected with *Route Model binding*
public function show(Request $request, User $user) {
   $this->ensureOwnsPage($user);
   // Everything fine, user owns the page so serve the page
}

protected function ensureOwnsPage($user) {
   if (Auth::user()->id !== $user->id) {
      throw new Exception("Unauthorized access");
   }
}

Or even better... put the authorization logic into Controller using controller filter: https://laravel.com/docs/4.2/controllers#controller-filters

jusahah87 left a reply on CRUD: Restrict Access By User Id

@afujita This is pretty common scenario. I usually do this using middleware:

// App/Http/Middleware/CheckUserIsAccessingHisOwnPage.php
public function handle(Request $request, Closure $next) {
   $userID = $this->route('user');
   if (Auth::user()->id === $userID) {
      // All is fine, user is accessing his own page
      return $next($request);
   }
   // User is trying to access somebody elses page
   Session::flash('warning', 'Not your page - access denied');
   return redirect('home');
}

Then apply that middleware to a suitable route group you want to protect.