moses

Experience

5,630

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 0 Lessons Completed
  • 0 Favorites

8th April, 2018

moses left a reply on How Can I Solve Case-sensitive Where Like Statement On Json Data In Laravel Eloquent? • 2 months ago

@jlrdw I try this : Order::whereRaw('LOWER(information->"$.owner") like "%?%"', strtolower($receipt)) ->paginate(5);. But it's the same

moses left a reply on How Can I Solve Case-sensitive Where Like Statement On Json Data In Laravel Eloquent? • 2 months ago

@jlrdw I need a spesific answer. Because I had try it. But it's the same

7th April, 2018

moses started a new conversation How Can I Solve Case-sensitive Where Like Statement On Json Data In Laravel Eloquent? • 2 months ago

I use Laravel 5.6 and mysql database.

My Laravel eloquent query is like this:

Order::where('information->owner', 'like', '%'.$receipt.'%')->paginate(5);

Information field is a JSON type.

{"owner": "Chelsea"}

If $receipt is Chel, the query returns a result.

But if $receipt is chel or CHEL, the result is empty

How can I solve this problem?

14th March, 2018

moses left a reply on How Can I Validation Object String With Validation Laravel? • 3 months ago

@jcmargentina There exist error like this : The given data was invalid. The selected data.name field is required. The selected data.gender field is required. etc. Whereas I had fill the data

moses started a new conversation How Can I Validation Object String With Validation Laravel? • 3 months ago

I use laravel 5.6

I use https://laravel.com/docs/5.6/validation#form-request-validation to validation server side

My controller like this :

<?php
....
use App\Http\Requests\UserUpdateRequest;

class UserController extends Controller
{
    ...
    public function update(UserUpdateRequest $request)
    {
        // dd($request->all());
    }
}

Before run statement in the update method, it will call UserUpdateRequest to validation server side

The validation like this :

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserUpdateRequest extends FormRequest
{
    ....
    public function rules()
    {
        dd($this->request->all());
        return [
            'name'          => 'required|max:50',
            'gender'        => 'required',
            'birth_date'    => 'required',
            'address'       => 'required',
            'status'        => 'required'
        ];
    }
}

The result of dd($this->request->all()); like this :

Array
(
    [selected_data] => {"name":"agis","gender":"2","birth_date":"2018-03-13","address":"london"}
)

How can I validation if the data is object array like that?

moses started a new conversation How Can I Upload File Using Vuex Store On The Vue Component? • 3 months ago

If I using ajax in vue component like this :

<template>
    <div>
        ...
    </div>
</template>
<script>
    export default {
        methods: {
            submitForm() {
                ...
                formData.append('file', files)
                axios.post(this.baseUrl+'/member/profile/update',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
                ).then(function(response) {
                    console.log('success')
                })
                .catch(function(error) {
                    console.log('fail')
                })
            }
        }
    }
</script>

It works. I successfully get the file

But here I want to using vuex store

My pattern of vuex store like this :

I change my vue component like this :

<template>
    <div>
        ...
    </div>
</template>
<script>
    export default {
        methods: {
            submitForm() {
                ...
                formData.append('file', files)
                this.updateProfile({formData, reload: true})
            }
        }
    }
</script>

In the component vue, it will call updateProfile method in modules user

The modules user like this :

import { set } from 'vue'
import users from '../../api/users'
import * as types from '../mutation-types'
// initial state
const state = {
    addStatus:null
}
// getters
const getters = {
    updateProfileStatus: state =>  state.addStatus,
}
// actions
const actions = {
    updateProfile ({ dispatch,commit,state },{user,reload})
    {
        users.updateProfile(user,
            response => {
                commit(types.UPDATE_PROFILE_SUCCESS)
            },
            errors => {
                commit(types.UPDATE_PROFILE_FAILURE)
            }
        )
    }
}
// mutations
const mutations = {
    [types.UPDATE_PROFILE_SUCCESS] (state){
        state.addStatus = 'success'
    },
    [types.UPDATE_PROFILE_FAILURE] (state){
        state.addStatus = 'failure'
    }
}
export default {
    state,
    getters,
    actions,
    mutations
}

From the modules user, it will call updateProfile method in api users

The api users like this :

import Vue from 'vue'
export default {

    updateProfile (user, cb, ecb = null) {
        axios.post('/member/profile/update', user)
            .then(response => cb(response))
            .catch(error => ecb(error))
    }
}

So my pattern like that. So i'm using pattern of vuex store

My problem here is I'm still confused to send file data

If I console.log(user) in the updateProfile method on modules user, the result is undefined

How can I send file data using vuex store?

8th March, 2018

moses left a reply on Why Return Is Not Working In The Img.onload On The Vue Component? • 3 months ago

@topvillas I'm still confused to implement the promise. Please answer with the code

moses started a new conversation Why Return Is Not Working In The Img.onload On The Vue Component? • 3 months ago

I have vue component like this :

<template>
    <section>
        ...
    </section>
</template>
<script>
    export default {
        ...
        data() {
            return {
                allowableTypes: ['jpg', 'jpeg', 'png'],
                maximumSize: 4000000
            }
        },
        methods: {
            ...
            onFileChange(e) {
                if (this.validate(e.target.files[0])) {
                    let files = e.target.files,
                        reader = new FileReader()
                    // if any values
                    if (files.length){
                        reader.onload = (e) => {
                            this.image = e.target.result
                        }
                        reader.readAsDataURL(files[0])
                    }
                }
            },
            validate(image) {
                // validation file type  
                if (!this.allowableTypes.includes(image.name.split(".").pop().toLowerCase())) {
                    return false
                }
                // validation file size
                if (image.size > this.maximumSize) {
                    return false
                }
                // validation image resolution
                let img = new Image()
                img.src = window.URL.createObjectURL(image)
                let self = this
                img.onload = function() {
                    let width = img.naturalWidth,
                        height = img.naturalHeight

                    window.URL.revokeObjectURL(img.src)

                    if(width != 850 && height != 350) {
                        return false
                    }
                }
                return true
            }
        }
    }
</script>

If user upload image, it will call onFileChange method. Before display the image, it will call method validate to validate the image

I try validate file size and file type and it works

My problem here is validate the resolution

From my code, it seems my code is true

But I try like this :

I upload image with width = 100, height = 100

From the code, should it return false

But when I run my code, it return true

Seems return is not working in the img.onload

How can I solve this problem?

3rd March, 2018

moses started a new conversation How Can I Upload Image Using Storage::put On The Laravel? • 3 months ago

My code to upload image like this :

$file = $file->move($path, $fileName);

The code works

But I want to change it using Storage::put like this reference :

https://laravel.com/docs/5.6/filesystem#storing-files

I try like this :

Storage::put($fileName, $path);

It does not works

I'm confused, where I must put $file on the code

How can I solve this problem?

24th February, 2018

moses left a reply on How Do I Upload Files On 2 Folders At Once In One Method On The Laravel? • 3 months ago

@skliche Thanks a lot. It works

moses started a new conversation How Do I Upload Files On 2 Folders At Once In One Method On The Laravel? • 3 months ago

I use laravel 5.6

I want to upload files on 2 folders at once. So if the image uploaded successfully in the product folder, I want the image uploaded in the thumbs folder as well

I try like this :

public function uploadImage($file)   
{
    if($file) {
        $fileName = str_random(40) . '.' . $file->guessClientExtension();
    }

    $destinationPath = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product';

    if(!File::exists($destinationPath)) {
        File::makeDirectory($destinationPath, 0755, true);
    }

    $file->move($destinationPath, $fileName);

    $destinationPathThumb = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR . 'thumb';

    if(!File::exists($destinationPathThumb)) {
        File::makeDirectory($destinationPathThumb, 0755, true);
    }

    $image_resize = Image::make($file->getRealPath());  
    $image_resize->resize(300, 300);
    $image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);
    
    return $fileName;
}

If the code run, it just success to upload in the product folder. It did not upload in the thumbs folder

There exist error like this :

message Unable to find file (/tmp/phpUSxbEJ).

exception Intervention\Image\Exception\NotReadableException

I try run this code :

public function uploadImage($file) 
{
    if($file) {
        $fileName = str_random(40) . '.' . $file->guessClientExtension();
    }
    $destinationPathThumb = storage_path() . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'product' . DIRECTORY_SEPARATOR . 'thumb';

    if(!File::exists($destinationPathThumb)) {
        File::makeDirectory($destinationPathThumb, 0755, true);
    }
    $image_resize = Image::make($file->getRealPath());  
    $image_resize->resize(300, 300);
    $image_resize->save($destinationPathThumb . DIRECTORY_SEPARATOR . $fileName);
    return $fileName;
}

So I remove code to upload in product folder. I try it and it works. It success upload on the thumbs folder

So I think in one process, it only upload in one folder

Is there any other way to upload on 2 folders?

21st February, 2018

moses started a new conversation How Can I Call View Blade Laravel In Vue Component? • 4 months ago

My view blade laravel like this :

<section class="content">
    <product-list :product-data="{{json_encode($products)}}"></product-list>
</section>

In the view blade call vue component

The vue compoponent like this :

<template>
    <div class="box">
        ...
        <div class="box-body">     
            <div class="box-footer">
                <!-- call view blade -->
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        ...
    }
</script>

In the vue component, I want to call view blade laravel

The view blade like this :

{{$products->links()}}

I want to call it because the pagination only run in view blade

How can I do it?

moses started a new conversation How Can I Display Pagination Laravel On The Vue Component? • 4 months ago

My controller like this :

public function index()
{
    $products = $this->product->list(); 
    dd($products);
    return view('admin.product.index',compact('products'));
}

The result of dd($products); like this : https://postimg.org/image/w39usbfrv/

My view blade laravel like this :

<section class="content">
    <product-list :product-data="{{json_encode($products)}}" :page="{{json_encode($products->links())}}"></product-list>
</section>

My vue component product list like this :

<template>
    <div class="box">
        ...
            <table class="table table-list">
                ...
                <tr v-for="item in products" :key="item.id">
                    <td>{{item.name}}</td>
                    <td>{{item.createdAt}}</td>
                    <td>{{item.updatedAt}}</td>
                </tr>
                ...
            </table>
            <div class="box-footer">
                ...
                    {{this.page}}
                ...
            </div>
        ...
    </div>
</template>
<script>
    export default {
        props: ['productData','page'],
        data(){
            return {
                ...
                products: this.productData.data,
            }
        },
        ...
    }
</script>

If I run the code, the result of {{this.page}} is empty

If this : {{$products->links()}} placed in view laravel it works

But if it passed on the vue component, the result is empty

How can I solve this problem?

Note :

I know how to use ajax request. But I don't use it. Here I just want to try the another way

moses left a reply on How Can I Pass Pagination Data And Array From Controller Laravel To Vue Component? • 4 months ago

@bobbybouwmann I just want to try it. There exist error like this : "htmlspecialchars() expects parameter 1 to be string, array given (View: /home/vagrant/code/my-app/resources/views/admin/product/index.blade.php)"

moses started a new conversation How Can I Pass Pagination Data And Array From Controller Laravel To Vue Component? • 4 months ago

My controller like this :

public function index()
{
    $products = $this->product->list(); 
    dd($products);
    return view('admin.product.index',compact('products'));
}

The result of dd($products); like this : https://postimg.org/image/w39usbfrv/

My view blade laravel like this :

<section class="content">
    <product-list :products="{{$products}}" test="test"></product-list>
</section>

My vue component product list like this :

<template>
    <div class="box">
        ...
    </div>
</template>
<script>
    export default {
        props: ['products','test'],
        mounted(){
            console.log(this.test)
            console.log(this.products)
        }
        ...
    }
</script>

If I run the code, on the console just display result ofconsole.log(this.test)

The result of console.log(this.products) is not display

Why it not display?

How can I solve this problem?

15th February, 2018

14th February, 2018

moses left a reply on How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 4 months ago

@sutherland I am still confused. Because when I try on my localhost, it works. This just does not work when run the send mail on the staging server

moses left a reply on How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 4 months ago

@Snapey In my localhost, it works. This just does not work on the staging server.

moses left a reply on How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 4 months ago

@Snapey Then what is the right solution to solve my problem?

13th February, 2018

moses left a reply on How Can I Solve "We Were Unable To Obtain A LetsEncrypt SSL Certificate On Your Server" On The Forge Laravel? • 4 months ago

@bobbybouwmann I want to try it first. My server using digital ocean, forge laravel and gitlab. Where can I add sub domains in my dns? Is it in digital ocean? Or using ssh via putty?

moses left a reply on How Can I Solve "We Were Unable To Obtain A LetsEncrypt SSL Certificate On Your Server" On The Forge Laravel? • 4 months ago

@bobbybouwmann So, what should I do? Do I have to add my domain in DNS? How to? I need a detailed answer. Because I just first take care of the problem on the server. Before I just write code only

moses left a reply on How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 4 months ago

@VijayKadiyam No. I don't remove it. I had run it. But it's the same

12th February, 2018

moses left a reply on How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 4 months ago

@biishmar Like description in my question above. I had try it all, but it's the same

moses started a new conversation How Can I Solve "Connection Could Not Be Established With Host Smtp.gmail.com"? • 4 months ago

If I do send email on the my localhost, it works. No error

But I try on the staging server, it display error like this :

Swift_TransportException in StreamBuffer.php line 268:
Connection could not be established with host smtp.gmail.com [Connection timed out #110]

in StreamBuffer.php line 268
at Swift_Transport_StreamBuffer->_establishSocketConnection() in StreamBuffer.php line 62
at Swift_Transport_StreamBuffer->initialize(array('protocol' => 'tcp', 'host' => 'smtp.gmail.com', 'port' => '587', 'timeout' => '30', 'blocking' => '1', 'tls' => true, 'type' => '1', 'stream_context_options' => array())) in AbstractSmtpTransport.php line 113
at Swift_Transport_AbstractSmtpTransport->start() in Mailer.php line 79
at Swift_Mailer->send(object(Swift_Message), array()) in Mailer.php line 395
at Mailer->sendSwiftMessage(object(Swift_Message)) in Mailer.php line 217
...

moses started a new conversation How Can I Solve "We Were Unable To Obtain A LetsEncrypt SSL Certificate On Your Server" On The Forge Laravel? • 4 months ago

My server using forge laravel(https://forge.laravel.com)

When I click obtain certificate button to add new certicate like this :

enter image description here

It does not work. There exist error like this :

We were unable to obtain a LetsEncrypt SSL certificate on your server

The full error like this :

enter image description here enter image description here

How can I solve this error?

30th October, 2017

moses started a new conversation How Can I Loop In Jquery Validate? • 7 months ago

My form use vue.js 2

The vue component like this :

<template>
    ...
    <li v-for="item in items">
        <input type="hidden" :name="'photo[' + item + ']'" :id="'photo-' +item">
        ...
    </li>
    ...
</template>

<script>
    export default {
        data() {
            return {
                items: [1,2,3,4,5]
            }
        }
        ...
    }
</script>

I have 5 box image to upload photo

For example :

If I upload photo on the first box, the name to be : photo[1]

If I upload photo on the second box, the name to be : photo[2]

etc

Here I did not give my photo upload code. I just give the code as necessary. In essence if user upload photo, it will save the file in temp and give value to input text each box

My problem is make dinamyc validate in jquery validate

I have validate.js like this :

...
product: {
    rules: {
        photo: {
            required: true,
        }
    },
    messages: {
        photo: 'Minimal 1 photo'
    },
    errorElement: 'span',
    errorPlacement: errorPlacement,
    highlight: highlight,
    unhighlight: unhighlight
},
...

Seems it will loop in jquery validate. But I'm still confused

Essentially at least 1 input text must have filename value. Otherwise there will be validation

How can I do it?

27th October, 2017

moses left a reply on How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

@bobbybouwmann, How can I copy them from the node_modules directory? Try to explain in detail. I still need to learn a lot :)

moses left a reply on How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

@bobbybouwmann, Actually I dont need to use gulpfile to copy it. I can directly store the summernote font data in public

moses left a reply on How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

@bobbybouwmann, Okay. Thanks a lot for your help. Its help me

moses left a reply on How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

@bobbybouwmann, Now it works. I try like this

In gulpfile.js like this :

.copy('resources/assets/css/font/summernote.eot', 'public/font/summernote.eot')
.copy('resources/assets/css/font/summernote.ttf', 'public/font/summernote.ttf')
.copy('resources/assets/css/font/summernote.woff', 'public/font/summernote.woff');

In summernote.css like this :

@font-face{font-family:"summernote";font-style:normal;font-weight:normal;
src:url("/font/summernote.eot?0d0d5fac99cc8774d89eb08b1a8323c4");
src:url("/font/summernote.eot?#iefix") format("embedded-opentype"),
url("/font/summernote.woff?0d0d5fac99cc8774d89eb08b1a8323c4") format("woff"),
url("/font/summernote.ttf?0d0d5fac99cc8774d89eb08b1a8323c4") format("truetype")}

Does that mean you?

moses left a reply on How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

@bobbybouwmann, Now the copy process work properly. If I run gulp watch, there exist file summernote.woff in folder public/font. But it is still not success call the font. Look at this : enter image description here

moses left a reply on How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

@bobbybouwmann, I had try it. But it does not work. After I run gulp watch, I check in folder public/font, there is no file summernote.woff

moses started a new conversation How Can I Solve Css/font/summernote.woff ... Net::ERR_ABORTED On Laravel? • 7 months ago

I want to implement summernote in my project. My project using laravel 5.3 & vue.js 2

I call js and css summernote by elixir laravel like this :

...
elixir(function (mix) {
  mix
      ...
      .sass([
          ...
          './resources/assets/css/summernote.css'
      ], 'public/css/style.css') // public
      .scripts([
          ...
          'plugins/summernote.min.js',
          'main.js'
      ])
      .webpack('app.js');
});

I edit in summernote.css like this :

@font-face{font-family:"summernote";font-style:normal;font-weight:normal;
src:url("/resources/assets/css/font/summernote.eot?0d0d5fac99cc8774d89eb08b1a8323c4");
src:url("/resources/assets/css/font/summernote.eot?#iefix") format("embedded-opentype"),
url("/resources/assets/css/font/summernote.woff?0d0d5fac99cc8774d89eb08b1a8323c4") format("woff"),
url("/resources/assets/css/font/summernote.ttf?0d0d5fac99cc8774d89eb08b1a8323c4")

I save font summernote like this :

enter image description here

If I execute the summernote, on the console exist error like this :

enter image description here

How can I solve the error?

The error it makes fonts in summernote not showing

4th September, 2017

moses started a new conversation How Can I Display Two Table In Email Layout Laravel 5.4? • 9 months ago

I want to customize Laravel 5.4 Notification Email Templates

https://medium.com/@adnanxteam/how-to-customize-laravel-5-4-notification-email-templates-header-and-footer-158b1c7cc1c

On the vendor/mail/html/message.blade, I try like this :

@component('mail::layout')
    {{-- Header --}}
    @slot('header')
        @component('mail::header', ['url' => config('app.url')])
            {{ config('app.name') }}
        @endcomponent
    @endslot

    {{-- Body --}}
    This is table one
    @component('mail::table')
    | Laravel       | Table         | Example  |
    | ------------- |:-------------:| --------:|
    | Col 2 is      | Centered      | $10      |
    | Col 3 is      | Right-Aligned | $20      |
    @endcomponent

    This is table two
    @component('mail::table')
    | Laravel       | Table         | Example  |
    | ------------- |:-------------:| --------:|
    | Col 2 is      | Centered      | $10      |
    | Col 3 is      | Right-Aligned | $20      |
    @endcomponent

    {{-- Subcopy --}}
    @isset($subcopy)
        @slot('subcopy')
            @component('mail::subcopy')
                {{ $subcopy }}
            @endcomponent
        @endslot
    @endisset

    {{-- Footer --}}
    @slot('footer')
        @component('mail::footer')
            &copy; {{ date('Y') }} {{ config('app.name') }}. All rights reserved.
        @endcomponent
    @endslot
@endcomponent

There are 2 tables. The first table appears well. But the second table, looks not neat. Seems the css does not work. And other than that the data after the table 1, the text is very small

The result of email layout like this :

enter image description here Why did it happen? Is my code is still wrong?

moses started a new conversation How Can I Display Image In Email Layout On The Laravel? • 9 months ago

My code to send email like this :

public function toMail($notifiable)
{
    return (new MailMessage)
                ->subject('Test')
                ->markdown('vendor.mail.markdown.message', ['data' => $this->data]);
}

My message.blade view like this :

@component('mail::layout')
    {{-- Header --}}
    @slot('header')
        @component('mail::header', ['url' => config('app.url')])
            {{ config('app.name') }}
        @endcomponent
    @endslot

    {{-- Body --}}
    This is your logo 
    ![Some option text][logo]
    [logo]: {{asset('img/my-logo.png')}} "Logo"  

    {{-- Subcopy --}}
    @isset($subcopy)
        @slot('subcopy')
            @component('mail::subcopy')
                {{ $subcopy }}
            @endcomponent
        @endslot
    @endisset

    {{-- Footer --}}
    @slot('footer')
        @component('mail::footer')
            &copy; {{ date('Y') }} {{ config('app.name') }}. All rights reserved.
        @endcomponent
    @endslot
@endcomponent

It success send email, but the contain of email like this :

This is your logo 
![Some option text][logo]

[logo]: http://myshop.dev/img/my-logo.png "Logo"

The image not display

How can I solve this problem?

I follow this reference : https://medium.com/@adnanxteam/how-to-customize-laravel-5-4-notification-email-templates-header-and-footer-158b1c7cc1c

3rd September, 2017

moses started a new conversation How Can I Solve NotFoundHttpException No Query Results For Model On Laravel? • 9 months ago

My code like this :

return redirect()->route('camp.don.summary', ['id'=>$dons->id]);

If the code executed, it will call route

The route like this :

Route::prefix('camp')->group(function(){
    ...
    Route::prefix('don')->group(function(){
        ...
        Route::get('summary/{id}', '[email protected]')->name('camp.don.summary');
    });
});

Then the route call controller

The controller like this :

public function summary($id)
{
    dd($id);
    return view('camp.don.summary.index');
}

On the browser, the url seems like this :

http://myapp.dev/camp/don/summary/31

And the content exist error like this :

(2/2) NotFoundHttpException No query results for model [App\Models\Camp] 31

How can I solve this error?

Seems my process is still wrong

30th August, 2017

moses left a reply on How Can I Solve Target [App\Repositories\NewsRepository] Is Not Instantiable While Building [App\Http\Controllers\Member\NewsController].? • 9 months ago

@jha, I had add it. Like this : Prettus\Repository\Providers\RepositoryServiceProvider::class

moses started a new conversation How Can I Solve Target [App\Repositories\NewsRepository] Is Not Instantiable While Building [App\Http\Controllers\Member\NewsController].? • 9 months ago

How can I solve Target [App\Repositories\NewsRepository] is not instantiable while building [App\Http\Controllers\Member\NewsController].?

5th March, 2017

moses left a reply on Why It Unable To Get Policies Working In Laravel 5.3? • 1 year ago

@PawelMysior, What is the parameter favorite?

moses left a reply on Why It Unable To Get Policies Working In Laravel 5.3? • 1 year ago

@PawelMysior, Like this : Route::get('favorite', 'Member\[email protected]');

moses left a reply on Why It Unable To Get Policies Working In Laravel 5.3? • 1 year ago

@PawelMysior,

Favorite {#498 ▼
  #fillable: array:3 [▼
    0 => "user_id"
    1 => "favoritable_id"
    2 => "favoritable_type"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
}

moses left a reply on Why It Unable To Get Policies Working In Laravel 5.3? • 1 year ago

@PawelMysior, My FavoriteController is like this :

<?php
use App\Models\Favorite;
...
class FavoriteController extends ApiController
{
    ...
    public function index(Favorite $favorite)
    {
        $this->authorize('view', $favorite);
        return view('profile.favorite');
    }
}

moses started a new conversation Why It Unable To Get Policies Working In Laravel 5.3? • 1 year ago

User table is like this :

enter image description here

Favorite table is like this :

enter image description here

My FavoritePolicy is like this :

<?php
namespace App\Policies;
use App\User;
use App\Models\Favorite;
use Illuminate\Auth\Access\HandlesAuthorization;
class FavoritePolicy
{
    use HandlesAuthorization;
    public function view(User $user, Favorite $favorite)
    {
        return $user->id === $favorite->user_id;
    }
}

When I add dd($user->id), the result is 1

1 is user id that is being logged

When I add dd($favorite->user_id), the result is null

Whereas based on the data in the favorites table, it should display 1

Why it displays null?

If I add dd($favorite), the result is like this :

Favorite {#498 ▼
  #fillable: array:3 [▼
    0 => "user_id"
    1 => "favoritable_id"
    2 => "favoritable_type"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: []
  #original: []
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  +exists: false
  +wasRecentlyCreated: false
}

From the above results, the records that have the user_id = 1, did not appear. Whereas it should appear

Is there anyone who can help me?

Reference : https://laravel.com/docs/5.3/authorization#writing-policies

4th March, 2017

moses started a new conversation How Can I Do Authorization Policies In Laravel 5.3? • 1 year ago

My FavoritePolicy is like this :

<?php
namespace App\Policies;
use App\User;
use App\Models\Favorite;
use Illuminate\Auth\Access\HandlesAuthorization;
class FavoritePolicy
{
    use HandlesAuthorization;
    public function view(User $user, Favorite $favorite)
    {
        return $user->id === $favorite->user_id;
    }
}

My FavoriteController is like this :

<?php
use App\Models\Favorite;
...
class FavoriteController extends ApiController
{
    ...
    public function index(Favorite $favorite)
    {
        $this->authorize('view', $favorite);
        return view('profile.favorite');
    }
}

My AuthServiceProvider is like this :

<?php
namespace App\Providers;
use App\Models\Favorite;
use App\Policies\FavoritePolicy;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        Favorite::class => FavoritePolicy::class,
    ];
    public function boot()
    {
        $this->registerPolicies();
    }
}

When I run my system to display favorite listing, there exist error like this :

Whoops, looks like something went wrong.

1/1 HttpException in Handler.php line 115: This action is unauthorized.

What the implementation of Authorization Policies is correct?

I try dd($user) in view method(FavoritePolicy), the result displays user data is being logged. It's true

But I try dd($favorite), the result does not display favorite data of the user who is currently logged. Whereas I check on the table, favorite data of the user who is currently logged is exist

How can I solve this problem?

21st February, 2017

moses started a new conversation How To Handle Laravel Eloquent "WHERE" Query With Slash On The Value? (Laravel 5.3) • 1 year ago

My table is like this :

enter image description here

On the mysql, I try like this :

SELECT * FROM players WHERE player_type = 'App\Models\Player'

Data does not showing

So, I add slash like this :

SELECT * FROM players WHERE player_type = 'App\\Models\\Player'

Data showing

Then, In laravel eloquent, I try like this :

$select = array(
    'player_type'
);
$query = self::where('player_type', '=', 'App\\\Models\\\Player')
             ->paginate(10, $select, 'page', null, null);

Data does not showing

How can I solve it?

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.