nemrut

nemrut

Member Since 7 Months Ago

Taipei

Experience Points 1,170
Experience Level 1

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

12 Sep
1 week ago

nemrut started a new conversation How Can I Get Model Name In Policies

I am trying to make a single Policy to handle all access permissions to models which they are asigned by AuthServiceProvider $policies . For example i have a Policy named "AccessPolicy" which looks like so :

// AuthServiceProvider
    protected $policies = [
        Role::class => AccessPolicy::class,
        Permission::class => AccessPolicy::class,
        Menu::class => AccessPolicy::class,
        Service::class => AccessPolicy::class,
    ];
// AccessPolicy
<?php

namespace App\Policies;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Access\HandlesAuthorization;

class AccessPolicy
{
    use HandlesAuthorization;

    private $model;
    
    public function viewAny(User $user)
    {
        return $user->can(str_slug(class_base($this->model)) . '-viewAny');
    }

What i am trying to do is being able to access Model name, so i can assign my $model variable to it. But for example viewAny only receives $user model but i also need the Eloquent Model which uses this policy.

Any idea?

nemrut left a reply on How To Convert An Array To Json With Array Value

found a way

'tags' => [
    'en' =>  json_encode([
        [
            'tag' => 'Tag 1 EN',
        ],
        [
            'tag' => 'Tag 2 EN',
        ]
    ]),
    'zh-cn' => json_encode([
        [
            'tag' => 'Tag 1 CH',
        ],
        [
            'tag' => 'Tag 2 CH',
        ]
    ]),
],

this gives me

{"en":"[{\"tag\":\"Tag 1 EN\"},{\"tag\":\"Tag 2 EN\"}]","zh-cn":"[{\"tag\":\"Tag 1 CH\"},{\"tag\":\"Tag 2 CH\"}]"}

nemrut started a new conversation How To Convert An Array To Json With Array Value

hi, i am trying to seed my db. One of the column is spatie's translatable so it is json formated table column. I need to set 2 languages which contains array of tags. so in my seeder i got


    $stores = [
            [
          
                'tags' => [
                    'en' => [
                        'tag' => 'Tag 1 EN',
                        'tag' => 'Tag 2 EN',
                    ],
                    'zh-cn' => [
                        'tag' => 'Tag 1 CH',
                        'tag' => 'Tag 2 CH',
                    ],
                ],
            ]
        ];

and my seeder is like:

 foreach (getStores() as $store) {
            $newStore = new Store;

            $newStore->setTranslations('tags', $store['tags']);

            $newStore->save();
        }
    }

but because spatie's translatable trait will do some converting during saving to db, so my data will be in tb like:

{"en":{"tag":"Tag 2 EN"},"zh-cn":{"tag":"Tag 2 CH"}} //missing tag 1

but i need it to be like:

{"en":"[{\"tag\":\"Tag 1 EN\"},{\"tag\":\"Tag 2 EN\"}]","zh-cn":"[{\"tag\":\"Tag 1 CH\"},{\"tag\":\"Tag 2 CH\"}]"}

as you can see, each language objects contains array . I am not sure how can i convert it to this format, any suggestions?

09 Sep
1 week ago

nemrut left a reply on How Can I Make This Code More Simple?

So i think i found the best approach by making a get mutator. So i could decode the json data. (by the way, i changed my attribute name from "info" to "infos" since it holds array of infos)

// Model
    public function getInfosAttribute($value)
    {
        return json_decode($value);
    }
// Controller
    public function index()
    {
        $maps = MapInfo::all();
        return view('pages.home')->with('maps', $maps);
    }
@extends('layout')
@section('content')
    @foreach ($maps as $map)
        <h1>{{$map->title}}</h1>
        @foreach ($map->infos as $info)
            <p>{{$info->item}}</p>
        @endforeach
    @endforeach
@endsection
08 Sep
1 week ago

nemrut left a reply on Switch Language Is Worked Only With Auth Laravel

try

public function handle($request, Closure $next)
{
    if ( Session::has('locale')) {
            $locale = $request->session()->get('locale');
    } else {
            $locale = 'en';
    }
    App::setLocale($locale);
    return $next($request);
}

nemrut left a reply on Laravel Nova Items Field Issue With Translations

I fixed my issue by changing the package i used. I actually found a package helps a lot and cool to use. It also translatable.

fourstacks/nova-repeatable-fields

https://github.com/fourstacks/nova-repeatable-fields

nemrut left a reply on How Can I Make This Code More Simple?

Well, i heavily use spatie/laravel-translatable and they store their values a json in db. Actually they wouldn't want to change the way they use because they said, they use it for their projects and they don't want to change.

nemrut left a reply on How Can I Make This Code More Simple?

Hmm, But $maps has other things that i need to use in the template. If i need to be clear:

@extends('layout')
@section('content')
    @foreach ($maps as $key => $value)
        <h1>{{$maps->title}}</h1>
        @foreach (json_decode($value->info,true) as $value)
            <p>{{$value['info']}}</p>
        @endforeach
    @endforeach
@endsection

As you can see, each map has a title, and info, each info has multiple lines. And info is actually spatie/translateable. So in database it's looks like this:

{"en":"[{\"info\":\"item 1\"},{\"info\":\"item 2\"}]","zh-cn":"[{\"info\":\"item 1\"},{\"info\":\"item 2\"}]"}

translateable trait handles the geting translated attributes. All i need to do is decode info in controller. and then deliver it to blade and loop to get the values.

I hope it's more clear now.

nemrut started a new conversation How Can I Make This Code More Simple?

Hi, I would like to make this code more simple way. Can you give me some tips?

// Home Controller
    public function index()
    {
        $maps = MapInfo::all();
        return view('pages.home')->with('maps', $maps);
    }
@foreach ($maps as $key => $value)
    @foreach (json_decode($value->info,true) as $value)
        {{$value['info']}}
    @endforeach
@endforeach

nemrut started a new conversation Laravel Nova Items Field Issue With Translations

I am trying to make translatable field using dillingham/nova-items-field package. But i couldn't figure out a way to do it. I am keep getting Array to string conversion error. Anyone can tell me a way?

// Model
namespace App;

use Illuminate\Database\Eloquent\Model;
use Spatie\Translatable\HasTranslations;

class MapInfo extends Model
{
    use HasTranslations;

    public $translatable =  ['title', 'info'];
    public $casts = [
        'info' => 'array'
    ];
}
// Nova Resource Fields
...
 public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
            Translatable::make([
                Text::make(__('Title')),
                Items::make(__('Info'))
            ]),
        ];
    }
// Observer
namespace App\Observers;

use App\MapInfo;
use Illuminate\Support\Facades\Log;

class MapInfoObserver
{
....
    function saving(MapInfo $mapinfo)
    {
        // not sure what to do here so i log and see the output
        Log::info($mapinfo);
    }
// Log file
[2019-09-08 05:30:03] local.INFO: {"title":{"en":"asd","zh-cn":"asd"},"translations_info_en":[],"translations_info_zh-cn":[],"floor_id":1}  
[2019-09-08 05:30:03] local.ERROR: Array to string conversion {"userId":1,"exception":"[object] (ErrorException(code: 0): Array to string conversion at /Users/muzafferdede/Desktop/Code/dts/vendor/laravel/framework/src/Illuminate/Support/Str.php:353)
[stacktrace]
#0 /Users/muzafferdede/Desktop/Code/dts/vendor/laravel/framework/src/Illuminate/Support/Str.php(353): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Array to string...', '/Users/muzaffer...', 353, Array)
#1 /Users/muzafferdede/Desktop/Code/dts/vendor/laravel/framework/src/Illuminate/Database/QueryException.php(56): Illuminate\Support\Str::replaceArray('?', Array, 'insert into `ma...')
#....

i believe it is something simple but i am too tired to find it out all night, please help :(

21 Apr
4 months ago

nemrut left a reply on Trying To Get Property Of Non-object

why you loop into single $user ? and are you trying to get firstname of customer or user? because you set costumer to the $user variable. So seems like your customer doesn't has a firstname attribute. try,

public function viewAssessment() {
        $user = Auth::user();
        $pdf = \PDF::loadView('print', compact('user'));
        return $pdf->stream('invoice.pdf');
}

and in view

<ul>
    <li>{{ $user->firstname }}</li>
    //or if trying to get user's customer's name
    <li>{{ $user->customer->firstname }}</li>
</ul>
20 Apr
4 months ago

nemrut left a reply on How To Pass Parameters To Model's Boot() Method

@FTIERSCH - Right, I just noticed, and corrected

trait HasSlug
{
    public static function bootHasSlug()
    {
        static::saving(function ($model) {
            $model->slug = str_slug($model->{$model->slugAttribute});
        });
    }
}

for your reference it's explained here: https://andy-carter.com/blog/using-laravel-s-eloquent-traits

Thank you.

nemrut left a reply on How To Pass Parameters To Model's Boot() Method

i manage to find a nicer way i guess.

trait HasSlug
{
    public static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
            $model->slug = str_slug($model->slugAttribute);
        });
    }
}

in model

class Service extends Model
{
    use HasTranslate,
        HasSlug;

    public $translatable = ['name', 'description'];
    public $slugAttribute = 'name';
...

I was trying to access $slugAttribute from boot method but somehow couldn't. Finally can access it like so.

nemrut left a reply on App Deployed. Yea! So Happens If I Add New Column To User Db

your way is a long way, just make new migration for the existing table as example

php artisan make:migration add_age_to_users_table

edit your new migration as your need

Schema::table('users', function (Blueprint $table) {
    $table->integer('age')->nullable(); //nullable because by default existing users doesn't has any value for the age column
});

then simply migrate

php artisan migrate

your users table will have the new 'age' column and no data will be erased

nemrut left a reply on How To Pass Parameters To Model's Boot() Method

i could manage to make it work in the trait by changing like so:

trait HasSlug
{

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

        static::saving(function ($model) {
            $model->slug = str_slug($model->{self::$slugName});
        });
    }
}

and in the model defining $slugName as static property



class Service extends Model
{
    use HasTranslate,
        HasSlug;

    public $translatable = ['name', 'description'];

    public static $slugName = 'name';
....

Not sure if this is proper way but so far it's works. I wanted to ask here if there is anything Laravel specific, as you mention that adding a bootHasSlug method as away but that will be static as well, so i guess will be the same result. what you think?

nemrut started a new conversation How To Pass Parameters To Model's Boot() Method

Hi, i am trying to make a dynamic slug trait so i can use on all of my sluggable models. For now i am checking via hardcoding without passing any data from model and just checking as:

namespace App\Traits;

trait HasSlug
{

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

        static::saving(function ($model) {
            $slugName = $model->title;
            if (!$model->title) {
                $slugName = $model->name;
            }
            $model->slug = str_slug($slugName);
        });
    }
}

what i would like to do is make the slugName variable pass from model as:

class Service extends Model
{
    use HasTranslate,
        HasSlug;

    public $translatable = ['name', 'description'];

    public $slugName = 'name';

    public function works()
    {
        return $this->belongsToMany(Work::class);
    }
}

and use it in the boot method. But i can't figure out how static methods works. Could you give me some suggestions? thanks