Cinek

Cinek

Member Since 2 Years Ago

Experience Points
25,640
Total
Experience

4,360 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
1
Lessons
Completed
Best Reply Awards
43
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 6
25,640 XP
29 Nov
9 months ago

Cinek left a reply on API That Returns JSON

simply name this relations

public function information

and

public function pictures

and then

$resort = Resort::with('information','pictures')->find($id);
        return response()->json(
            $resort
        );

and it's should work. Besides, it's better to use API resources. You can read more about it: https://laravel.com/docs/5.7/eloquent-resources

28 Nov
9 months ago

Cinek left a reply on Models HasMany

What do you want to do?

Cinek left a reply on Convert Custom Non Eloquent Model To Json

You can implement JsonSerializable interface and define how to jsonify object in jsonSerialize method.

class MyObject implements \JsonSerializable {
public function jsonSerialize()
    {
        return [
            'title' => $this->title
        ];
    }
}
26 Sep
11 months ago

Cinek left a reply on Save Votes Of A Model In Database

"doesn't work properly" What does it mean? Any errors?

Cinek left a reply on Model Events In Database Seeder

user_id column is set to not null so when model events are enabled there's an error on user_id constraint - Auth::user() is null so can't attach null user to group.

Cinek started a new conversation Model Events In Database Seeder

Hi, I have one confusion. I have 2 models: User and Group. Group have user_id which means owner of this group. I fill this ID in GroupObserver in creating function

$group->user()->associate(Auth::user());

I have problem because it will fail:

        factory(\App\Models\Group::class, 10)->create();

while seeding there is not logged user. I assigned user to group in GroupFactory and disable all events on Group model but I think there's a better way to workarround this problem.

24 Sep
11 months ago

Cinek left a reply on One To Many Relationship

@foreach($designations as $designation)
{{$designation->departments->name}}
@endforeach

By the way departments relationship in Designation model should be in singular form because designation has one department, not many.

18 Sep
1 year ago

Cinek left a reply on I Wanna Get All Articles With Votes

Try this

 $articles = Article::with('user', 'categorie', 'comments', 'votes')
            ->withCount('votes', 'cryptoVotes')
            ->where('created_at', '<=', Carbon::now()->subHour(1))
            ->has('crypto_votes_count', '>', 5)
            ->paginate(20);
16 Sep
1 year ago

Cinek started a new conversation Chat's Database Structure

Hello, I have one problem with designing database structure for my app. I have 3 models: Events, groups and users. Relations: Events - Users - many to many Groups - Users - many to many

There will be available one chat withing group and one inside event. Additonally in the near future I am going to implement chats between two or more users.

i'm a bit confused what is the best way to design it. I created Chat model and many to many relation between chat and users.

1 idea: The members of group and event chats will be stored in respectively event_users and group_users tables. Only chats between users will be stored in chat_users.

Second idea: chat_users will be synchronized with event_users and group_users tables. The advantage of this way is that I will have simple separated logic to manage chats and there will be not many complicated queries to DB.

Thanks for any feedback or maybe other ideas

28 Aug
1 year ago

Cinek left a reply on Many To Many In RestFUL API

Do you mean that user_groups should be separate resource in API and to store invitations in another table? Something like this?

  • GET /users - get list of users
  • GET /users/{userId} - get user details
  • GET /user_groups - all user_groups
  • GET /user_groups - all user_groups
  • GET /user_groups/{id} - details
  • POST user_groups - add user to group
  • PUT user_groups - update user role in group
  • GET group_invitations - group_invitation
  • GET group_invitations/{id} - detail of invitation
  • POST group_invitations - add invitation
  • DELETE group_invitations - delete invitation
  1. Now can how to get all of groups of specific user? /users/{userId}/groups or /user_groups?user_id={id}
27 Aug
1 year ago

Cinek left a reply on Global Partial Routes On Resources

According to the sources:

 public function resources(array $resources)
    {
        foreach ($resources as $name => $controller) {
            $this->resource($name, $controller);
        }
    }

I think you have to define your resource routes separatly.

Cinek left a reply on Accessing A Page If You're Within A Specific IP Address Range?

public function handle($request, Closure $next)
    {
        $startIp = ip2long('192.168.1.1');
        $endIp = ip2long('192.168.1.100');
    $requestIp = ip2long($request->ip());
        if($requestIp >= $startIp && $requestIp <= $endIp){
            abort(404);
        }
        return $next($request);
}

Cinek started a new conversation Many To Many In RestFUL API

I have 2 tables:

  • user(id,name)
  • group(id,name)
  • user_groups(id,user_id,group_id,status,role)

In the user_groups table there can be only one entry with given user_id and group_id. When user is invited to group there should be created user_groups entry with status = 0. When user accepts invitation status should change to 1. My question is how to design restful routes to this situation. How to add/edit entries in user_groups table?

26 Aug
1 year ago

Cinek left a reply on Method Update Does Not Exist (Event Destroy Method)

update method will not work on collection of models, only on single model or query builder.

You can do this:

 $participants = $event->participants()->update([ 
                    'status_id' => 5, 
                ]);

I have removed where condition because participants() should do this.

23 Aug
1 year ago

Cinek left a reply on How Can I Update Just The Changes In Model?

$userData = $request->only('first_name','last_name','username');
$user->update($userData);

Cinek started a new conversation RequestHandled Event

I'm using Lumen 5.6 and I write package which will add some extra values to JSON responses. In laravel there is a Illuminate\Foundation\Http\Events\RequestHandled event but I can't find it in Lumen. Is there any similar event in Lumen? Temporarily I created my own event and I dispatch it in middleware but I don't think so it is a good solution.

07 Aug
1 year ago

Cinek left a reply on Get OnlyTrashed() Does Not Exist In Query Builder

What version of laravel do you use?

02 Aug
1 year ago

Cinek left a reply on Relations In Model Events

Thanks for response :) It's only my thoughts. I'm learning how laravel works. I thought that an object is passed to event listener with all it properties but it's not. I'd like to find out why this is happening, not find a workarround of this situation.

Cinek left a reply on Laravel Updating Relationship Column In WhereHas

$unused = Sale::whereHas('salesdetails',function($query) {
             $query->where('product_id', '<=', 24)->where('switch', 1);
        })->where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now)

This query returns a Sale models so you are performing update switch on sales table. You should start your query from SalesDetails model, something like this:

SalesDetail::whereHas('sale', function ($query) use ($now) {
            $query->where(DB::raw("(DATE_FORMAT(transaction_date,'%Y-%m-%d'))"), '<', $now);
        })->where('product_id', '<=', 24)->where('switch', 1)
            ->update(['switch' => 0]);
01 Aug
1 year ago

Cinek left a reply on Can Someone Show Me The Correct Way To Fix This Relationship

Your User <=> Skill relation seems to be "many to many" relation. https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

User.php

public function skills(){
        return $this->belongsToMany('App\Skill');
}

Skill.php

public function users(){
        return $this->belongsToMany('App\User');
}

and you don't have UserSkill model.

29 Jul
1 year ago

Cinek left a reply on Laravel Route Conflict

Laravel takes the first matching route. Placing search route above show route file should do the job.

Edit: Or you can do:

Route::get('/articles/{article}', '[email protected]')->name('articles.show')->where('article', '!=','search');
26 Jul
1 year ago

Cinek left a reply on Raw Sql To Eloquent

By the way it seems to me that the relation User-> Favorite -> Post should be manyToMany with favorite table as a pivot

Cinek left a reply on Raw Sql To Eloquent

The fastest way to find all post favoured by logged user:

$post = Post::whereHas('favourite', function($query){
            $query->where('user_id', Auth::id());
        })->get();

This code will generate query select * from `posts` where exists (select * from `favourites` where `posts`.`id` = `favourites`.`post_id` and `user_id` = '1')

25 Jul
1 year ago

Cinek left a reply on Why In The Payment_c Column Is Stored 0 And Not 1?

What type is column payment_mb and payment_c in database?

Cinek left a reply on Get Districts Through Councils Relationship

Sorry, my mistake, I missunderstood.

Make relation to Council in Job model:

public function council(){
        return $this->belongsTo(Council::class, 'county_id');
    }

and then

$jobs = Job::with('council.district')->get();
foreach($jobs as $job) {
echo $job->council->district->name;
}

Cinek left a reply on Multiple Relationships Between Same Tables.. Naming And Syntax

@baguus you can do it with withDefault method introduced in laravel 5.5 https://laravel.com/docs/5.6/eloquent-relationships#default-models

public function mainDistributorUsers()
    {
        return $this->hasOne(User::class, 'id', 'main_distributor_id')->withDefault([
            'username' => 'Default username' //or place another name when main_distributor_id is null
        ]);
    }

and if your company will have null in main_distributor_id then $company->mainDistributorUsers->username will show "Default username".

Cinek left a reply on Get Districts Through Councils Relationship

Same as in County model.

Cinek left a reply on Multiple Relationships Between Same Tables.. Naming And Syntax

<td>{{ $company->mainDistributorUsers->username }}</td>

seems to be correct. You are sure that all your companies have a main_distributor_id field filled in? If one of the company will have null in main_distributor_id it will thrown exception.

Cinek left a reply on Interesting Question With Model In Laravel

You can set database connection on the fly:

$model1 = (new Model)->setConnection('mysql')->first();

or in static context

$model2 = Model::on('mysql')->first();
24 Jul
1 year ago

Cinek left a reply on Going Down Multiple Relationship Layers

$page = Page::with('boxes.item')->where('id',$id)->first();
18 Jul
1 year ago

Cinek left a reply on Ordering With Eloquent

Simply use orderBy function twice:

->orderBy('field1','asc')->orderBy('field2','desc')

It will generate order by field1 asc, field2 desc

13 Jul
1 year ago

Cinek left a reply on Retrieving BelongsTo Relationship

You should use

$assignment->category

(without brackets).

10 Jul
1 year ago

Cinek left a reply on [L5.*] Pagination: Change URL Query Name "page" Globally

Third parameter of paginate method do this

->paginate($limit,['*'],'seite')
09 Jul
1 year ago

Cinek left a reply on Track Changes In A Model And Store In Other Table

->map(function ($value, $field) use ($func) {
                return call_user_func_array($func, [$value, $field]);
             })

change to

->map(function ($value, $field) use ($func,$model) {
                return call_user_func_array($func, [$value, $field,$model]);
             })

and

protected function getHistoryBody($value, $field)
    {
        return [
            'body' => "Updated {$field} to ${value}",
        ];
    }

to

protected function getHistoryBody($value, $field, $model)
    {
$oldValue = $model->getOriginal($field);
        return [
            'body' => "{$field} Updated From {$oldValue} to {$value}",
        ];
    }
08 Jul
1 year ago

Cinek left a reply on Variables Refer To The Same Value

You have to change = to == in if condition

By the way you also have mixed up descriptionde and descriptionen

Cinek left a reply on Laravel 5.6 Pass String To Blade Component Is Object ?

No, only if you inject data into component via @slot directive. For example, if you pass a variable from controller you don't need to use toHtml method.

07 Jul
1 year ago

Cinek left a reply on Maintenance Mode Events?

I don't know if that event is available but you can override it in service provider.

AppServiceProvider

$this->app->extend('command.down', function () {
            return new MyCustomDownCommand();
        });
use Illuminate\Foundation\Console\DownCommand;

class MyCustomDownCommand extends DownCommand
{
    public function handle()
    {
        $this->comment('my php artisan down handler');
        parent::handle();
    }
}

and similarly you can do it with UpCommand

Cinek left a reply on Laravel On Centos7/Apache

I assume these permissions are from before you setting sudo chmod -R 777 /var/. Is the /var/www/html/checkers/storage/framework/views/ directory exists?

05 Jul
1 year ago

Cinek left a reply on Edit API Response

Why do want to have property quiz_name twice in second JSON ?

Cinek left a reply on Trying To Set Up Download For Pdf In My Db

Show code how do you upload your pdf

Cinek left a reply on Condition Based Iteration Using For Loop In JavaScript

If you want to go into next iteration you can use continue; statement:

if(audio.ended == true) {
            continue;
        }

Cinek left a reply on When I Want Download Excel?

Show your line 62 in Reports.php

Cinek left a reply on Modify An Instance Of Class Values Based On A Condition

for example:

$collection = collect([1,2,3]);
        $newCollection = $collection->map(function ($item, $key) {
            switch($item){
                case 1:
                    return 'YES';
                case 2:
                    return 'NO';
                case 3:
                    return 'MAYBE';
                default:
                    return '';
            }
        });
03 Jul
1 year ago

Cinek left a reply on Passing Variable From Middleware To Blade

Why do you want to pass variable to view in middleware? Better choice to passing variable to multiple views is to use View Composer

View::composer('*', function ($view) {
        $variable = 'value';
        $view->with('myvariable', $variable );
    });

Now you can use {{ $myvariable}} in all of your views.

Cinek left a reply on Querybuilder Pass Column To Nested Query

$events = Event::with('comments')->whereHas('comments',function ($query) {
            $query->whereColumn('comments.created_at','<','events.start');
        })->get();

whereColumn is function to compare columns in query.

Cinek left a reply on Using Sql Function In Laravel Eloquent

You can get te value returned by your function with this code

        $functionData = DB::select("select myfunction() as value");
        $category ->type = array_shift($functionData)->value;

If you want it to be done automatically after inserting category to DB place this code in laravel model observer:

class CategoryObserver
{
    public function created(Category $category)
    {
        $functionData = DB::select("select myfunction() as value");
        $category ->type = array_shift($functionData)->value;
        $category->save();
    }