Cinek

Cinek

Member Since 1 Year Ago

Experience Points 25,540
Experience
Level
Lessons Completed 1
Lessons
Completed
Best Reply Awards 43
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.

29 Nov
2 weeks 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

Cinek left a reply on API That Returns JSON

$resort = Resort::with('getInformation','getPictures')->find($id);
28 Nov
2 weeks 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
2 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();

because 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
2 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.

18 Sep
2 months 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
2 months 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
3 months 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?

  • /users - get list of users
  • users/{userId} - get user details

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}

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/{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
3 months 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($searchedIp >= $startIp && $searchedIp <= $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
3 months 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()->where('event_id', $event->id)->update([ 
                    'status_id' => 5, 
                ]);
23 Aug
3 months 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
4 months ago

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

What version of laravel do you use?

02 Aug
4 months 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 perform 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
4 months ago

Cinek left a reply on Database Wont Update

Can you see what the table timeouts and Timeout model looks like?

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
4 months 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.

26 Jul
4 months 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
4 months 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?

Cinek left a reply on Get Districts Through Councils Relationship

Sorry, my mistake, I missunderstood.

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

public function mainDistributorUsers()
    {
        return $this->hasOne(User::class, 'id', 'main_distributor_id')->withDefault([
            'username' => 'Default username' //or place another name with 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
4 months ago

Cinek left a reply on Going Down Multiple Relationship Layers

$page = Page::with('boxes.item')->where('id',$id)->first();
18 Jul
4 months 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
5 months ago

Cinek left a reply on Retrieving BelongsTo Relationship

You should use relation as an attribute

$assignment->category

(without brackets).

12 Jul
5 months ago

Cinek left a reply on Undefined Variable

Why have you

$message->string('message');

not

$table->string('message');

?

10 Jul
5 months ago

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

Third parameter of paginate method do this

->paginate($limit,['*'],'seite')

Cinek left a reply on How To Setup Custom If Statement

Blade::if('isadmin', function () {
            return Auth::guard('admin')->check();
        });

and in blade

@isadmin
I'm admin
@else
I'm not admin
@endelseadmin

Blade::if('admin', function () { $role = Auth::guard('admin')->user()->role; return in_array($role, func_get_args()); });

in blade

@admin('manager', 'owner', 'administrator')

09 Jul
5 months 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
5 months ago

Cinek left a reply on Variables Refer To The Same Value

You have to change = to == :)

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
5 months 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?

06 Jul
5 months ago

Cinek left a reply on When I Want Download Excel?

If you do not paste any line of code we have no chance to help you.

05 Jul
5 months ago

Cinek left a reply on Edit API Response

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