s4muel

s4muel

Member Since 1 Year Ago

Experience Points 54,480
Experience
Level
Lessons Completed 372
Lessons
Completed
Best Reply Awards 29
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

16 Jan
14 hours ago

s4muel left a reply on Read More In Paragraph

@FATIMA1 - blade (html) part:

<p>
    {{ str_limit($post->description, 100, '') }}
    @if (strlen($post->description) > 100)
        <span id="dots">...</span>
        <span id="more">{{ substr($post->description, 100) }}</span>
    @endif
</p>

<button onclick="myFunction()" id="myBtn">Read more</button>

CSS part:

#more  {display:  none;}

JS part:

function myFunction() {
    var dots = document.getElementById("dots");
    var moreText = document.getElementById("more");
    var btnText = document.getElementById("myBtn");

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more";
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less";
        moreText.style.display = "inline";
    }
}

s4muel left a reply on Json Validation Failed For Valid Json

@TAPAS - you sure you send the json string as the 'specification' value?

Route::post('test', function () {
    try {
        $request = request();

        $request->replace(
            ['specification' => '{ "specification": [ { "type": [ { "type": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone", "shape": "Bar" } ], "basic": [ { "os": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone", "Sim": "Bar" } ] } ] }']
        );

        $validatedData = $request->validate(
            [
                'specification' => 'required|json',
            ]
        );
    } catch (\Illuminate\Validation\ValidationException $e) {
        dd($e->errors());
    }
    dd($validatedData);
});

calling POST (without any input, it will be set by the $request->replace(...)) gives me this:

array:1 [
  "specification" => "{ "specification": [ { "type": [ { "type": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone", "shape": "Bar" } ], "basic": [ { "os": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone", "Sim": "Bar" } ] } ] }"
]

if i set it to invalid json string, i get:

array:1 [
  "specification" => array:1 [
    0 => "The specification must be a valid JSON string."
  ]
]

s4muel left a reply on Json Validation Failed For Valid Json

you are missing the main JSON object braces

{
    "specification": [{
        "type": [{
            "type": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone",
            "shape": "Bar"
        }],
        "basic": [{
            "os": "Smartphone , Phablet , Notch Phone , Camera Phone , Selfie Phone",
            "Sim": "Bar"
        }]
    }]
}
15 Jan
1 day ago

s4muel left a reply on How Could I Extend Collection With Macros To Sum Times?

Collection::macro('sumTimes', function ($attribute) {  
  
  $sum = $this->reduce(function ($sum, $item) use ($attribute){  
          list($h, $m, $s) = explode(':', $item->work_time);  
          $sum['h'] += $h;  
          $sum['m'] += $m;  
          $sum['s'] += $s;  
          return $sum;  
     }, ['h' => 0, 'm' => 0, 's' => 0]);  
  
  
  $sum['m'] += floor($sum['s'] / 60);  
  $sum['h'] += floor($sum['m'] / 60);  
  $sum['s'] = $sum['s'] % 60;  
  $sum['m'] = $sum['m'] % 60;  
  
  return implode(':', $sum);  
 });  

  $test_json = '[  
 { "id": 5071, "user_id": 30, "work_date": "2018-12-03", "work_time": "20:43:59" }, { "id": 5072, "user_id": 30, "work_date": "2018-12-03", "work_time": "07:43:59" }, { "id": 5073, "user_id": 30, "work_date": "2018-12-03", "work_time": "18:43:59" }]';  

  $collection = collect($test_json);
  
 dd($collection->sumTimes('work_time'));

s4muel left a reply on How To Redirect Page When Page Has An Internal Error Laravel

edit the render() method in your app/Exceptions/Handler.php to something like this:

public function render($request, Exception $exception)
{   
    if ($this->isHttpException($exception) && $exception->getStatusCode() === 500)
    {
        return redirect('/');
    }

    return parent::render($request, $exception);
}
14 Jan
2 days ago

s4muel left a reply on Show New And Old Attributes

without getOriginal... why would you do that? you can clone the object, before a change, cast both objects to array and compare the attributes(values) by using array_diff + get the corresponding old/new data from the other object. but i would prefer the getOriginal approach

s4muel left a reply on How To Use Auto Increment

@FAREEDR - weird, should be storage>app>public>banner instead of storage>app>banner

...but anyway, please try this:

    <img src="{{ asset("storage/$banner->image") }}">

s4muel left a reply on How To Use Auto Increment

check the storage, do you have that linked? quote from the documentation:

Remember, if you are using the local driver, all files that should be publicly accessible should be placed in the storage/app/public directory. Furthermore, you should create a symbolic link at public/storage which points to the storage/app/public directory.

s4muel left a reply on How To Use Auto Increment

@FAREEDR - regarding the deleting, this should be enough:

Storage::delete($banner->image);

s4muel left a reply on How To Use Auto Increment

does it have to be the autoincrement id? if not, and a unique id is enough, than i suggest using the out-of-the-box store() method for file upload, here is the documentation: https://laravel.com/docs/5.7/filesystem#file-uploads

and here is an example:

$path = $request->file('avatar')->store('avatars');

public function store( BannerFormRequest $request)
    {
        if($request->hasFile('image'))
        {
            //the path will contain a uniquely generated ID which serves as a file name
            $path = $request->file('image')->store('banner'); //stores the file in the avatars folder on your default public disk configured in config/filesystems.php

        }

        $banner = new Banner ([
            'title'=> $request->get('title'),
            'image'=> $path
        ]);

        $banner->save();
        alert()->success('Success Message','Banner has been added!')->autoClose(3000);
        return redirect('admin/list-banner');
    }


s4muel left a reply on 2 Connections At Laravel Transaction Without Default Connection

DB::connection('blabla') ...

and

DB::connection('blabla2') ...

s4muel left a reply on Laravel Tinker Problem

Try creating a config file at ~/.config/psysh/config.php if not already there.

<?php
return [
  'usePcntl' => false,
];

source: https://github.com/bobthecow/psysh/issues/540#issuecomment-446480753

11 Jan
5 days ago

s4muel left a reply on Not Seeing How To Get Laravel Code Style In PHPStorm

@DAVESTEAD - the laravel-ide-helper is indeed mainly for the auto-completion and doesn't affect coding-style. even though i suggest to try that one too, helps me a lot in phpstorm.

s4muel left a reply on Not Seeing How To Get Laravel Code Style In PHPStorm

i tried many times to configure phpstorm properly to follow psr2, but it was so pain-in-the-ass.

i doesn't answer your question, but i gave up and end up using php-cs-fixer https://github.com/FriendsOfPHP/PHP-CS-Fixer with a git pre-commit hook, that runs it automatically before i commit.

10 Jan
6 days ago

s4muel left a reply on Location.href

<button class="btn btn-primary" onclick="location.href='{{ url("/form", $data["detail_id"]) }}'"> Apply2 </button>

s4muel left a reply on Updating One-to-one Relationship

to begin with: that's not one-to-one relationship, but one-to-many (one company can have many users) so you should use: $this->belongsTo('Company');for the User and $this->hasMany('User'); for the Company

then you can update the company like this:

$user = User::find(1);
$company = Company::find(1);

$user->company()->associate($company);

$user->save();

s4muel left a reply on How To Count Total Price In Any Table

Model::all()->sum('receive_amount');
09 Jan
1 week ago

s4muel left a reply on Laravel Encryption And Decryption Without APP Key

a kind of... but base64 is not an encryption, just an encoding, it doesn't make the data secure.

i this case i suggest just using base64_encode and base64_decode instead of encrypt/decrypt

s4muel left a reply on Laravel Encryption And Decryption Without APP Key

none i can think of (that serves as a data protection at the same time), if the data could be decrypted without a key, there is no purpose of encrypting it, or am i missing something?

s4muel left a reply on Users Tree

you should be fine with simple One To Many relationship on the same Users table

s4muel left a reply on Laravel Encryption And Decryption Without APP Key

nope, that's kind of a point of it. you need to make sure, you don't lose it

08 Jan
1 week ago

s4muel left a reply on Remove Keys From Collection

as i said, there will always be indices. but the diff works as expected:

$rgbColors = collect(['red', 'green', 'blue']);  
$colors = collect(['red', 'cyan', 'yellow', 'blue']);  

dump($rgbColors);
/*
Collection {#448 ▼
  #items: array:3 [▼
    0 => "red"
    1 => "green"
    2 => "blue"
  ]
}
*/

dump($rgbColors->diff($colors));
/*
Collection {#453 ▼
  #items: array:1 [▼
    1 => "green"
  ]
}
*/

dump($rgbColors->diff(['green']));
/*
Collection {#453 ▼
  #items: array:2 [▼
    0 => "red"
    2 => "blue"
  ]
}
*/

s4muel left a reply on How To Update A Table Without Primary Key?

DB::table('minyuko')
    ->where('orderbango', $orderhenkan->bango)
    ->where('denpyobango', $master)
    ->update(['denpyohakkoubi' => '1970-01-01 01:01:01']);

s4muel left a reply on Remove Keys From Collection

@petritr, sorry, this is not possible. collection implements the ArrayAccess, so it's just and array on steroids, so every item need to be indexed.

06 Jan
1 week ago

s4muel left a reply on SQLSTATE[23000]: Integrity Constraint Violation: 19 NOT NULL Constraint Failed

regarding this screenshot: Screenshot 2019-01-06 17.03.03.png the POST parameter says, its District with capital D - that is weird, because i see that in the form you have <select name='district'> (with lovercase d), but somehow it gets in as District.

haven't you changed that recently?

05 Jan
1 week ago

s4muel left a reply on Polymorphic Relations Help

i would use a User table for common columns and then one-to-one relationship for the profile details (depending on the role,) as you suggested.

or depending un the further use, just a single column in User table with any JSON profile data might be enough?

04 Jan
1 week ago

s4muel left a reply on Json In Db Being Returned With Triple Quotes

it shouldn't matter if it is Json, pure dd("\nTEST"); should be returned with triple quotes as well

multi-line variables are enclosed in three double-quotes (don't ask me why, but probably for better readability?), relevant code in the VarDumper library: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/VarDumper/Dumper/CliDumper.php#L218

or have a look in the multi-line examples here: https://symfony.com/doc/current/components/var_dumper.html

but the empty array in $model->field bothers me more

s4muel left a reply on Date Of Posting Not Displayed On Mobile

@JLRDW - it doesn't show up for me too

s4muel left a reply on Route Suggestion

Route::get('{category}-suppliers-{country}', function($category, $country) {
    dump($category);
    dump($country);
    
    return 'Done';
})->where(['category' => '[\w\-]+', 'country' => '[\w]+']);

https://laravel.com/docs/5.1/routing#parameters-regular-expression-constraints

s4muel left a reply on Laravel With Html2canvas Not Saving The Picture

@JONJIE - oh, i see. there is a FileSystem class, that has put() method in it: https://laravel.com/api/4.2/Illuminate/Filesystem/Filesystem.html#method_put but it is just a wrapper on the file_put_contents, so i dont think it will make a big difference

03 Jan
1 week ago

s4muel left a reply on Vim ~/.zshrc Dose Not Work!

i am not skilled in the homestead, but it might not have zsh as default shell, try editing the bash config file instead vim ~/.bashrc

s4muel left a reply on Problems With Laravel And Apache2

try add this to your VirtualHost configuration. i think, the AllowOverride All directive will make a difference

<VirtualHost...>
...
    <Directory /var/www/blog/public>
        Options FollowSymLinks
        AllowOverride All
    </Directory>
...
</VirtualHost>

s4muel left a reply on Executing Commands From A Route File

i am afraid its only a CLI extension, so it wont work from apache calls. http://php.net/manual/en/pcntl.installation.php

s4muel left a reply on Passing Variables To A Function In Eloquent

            $query->whereDate('start_date', '<',$returndate)
                ->whereDate('end_date', '>',$startdate);
        })->get();
02 Jan
2 weeks ago

s4muel left a reply on How To Change Date Format Using Carbon

Do not return the value in the iteration, try to replace the $client->dob instead

01 Jan
2 weeks ago

s4muel left a reply on Laravel With Html2canvas Not Saving The Picture

@JONJIE - well the most simple way is to just specify any path you want in file_put_contents() but i suggest you make it more of a laravel way,

27 Dec
2 weeks ago

s4muel left a reply on Laravel With Html2canvas Not Saving The Picture

you are missing a CSRF token.

add this to your html (head) meta tag (e.g. in the index.blade.php file):

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

and set it to be send with every ajax call like this (in app.js):

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

and also make sure, the folder you are writing to, is writable. the file_put_contents('1.jpg', base64_decode($image[1])); just writes it to the public folder

27 Nov
1 month ago

s4muel left a reply on Testing How To Delete My Question In Laracast

yeah, "your friend", we get it ;)

s4muel left a reply on How To Escape "part Of" User Data...

1 - use the eloquent accessor in the Post model

    public function getBodyAttribute($value)
    {
        //do whatever manipulation you need with the $value
        return $value;
    }
21 Nov
1 month ago
20 Nov
1 month ago

s4muel left a reply on Eloquent Relations On UPDATE Cascade Or Not?

nope, you either set the constraint (if possible) or handle that manually

13 Nov
2 months ago

s4muel left a reply on Setting Carbon Config Based On User Settings

i would probably create a new middleware, that sets the carbon from user profile