samedi 31 août 2019

pass locale and model instance to some route

i have this route enter image description here

in blade i want send locale and feedback id to the route but i get this error:



Argument 1 passed to App\Http\Controllers\User\FeedbackController::edit() must be an instance of App\Comment, string given

but if i dont user locale and user just this i will work

 // works

i need pass locale variable too, how can in fix this?



via Chebli Mohamed

How to check if translatable are null (inside .blade)

I'm using dimsav/laravel-translatable

I have two tables Posts and PostTranslations The problem is when i go to localhost/en/posts the image $post->image still there even if $post->title (EN) is null

I want hide the image if $post->title (EN) or other translations are null. please, any help


      Schema::create('posts', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('image')->nullable();
                $table->unsignedBigInteger('user_id');
                $table->foreign('user_id')->references('id')->on('users');
                $table->timestamps();
            });



     Schema::create('post_translations', function (Blueprint $table) {
          $table->bigIncrements('id');
                $table->unsignedBigInteger('post_id')->unsigned();
                $table->string('locale')->index()->nullable();

                $table->unique(['post_id','locale']);
                $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

                $table->string('title')->nullable();
                $table->longText('text')->nullable();
                $table->string('slug')->unique()->nullable();




via Chebli Mohamed

How would I be able to get the foreign key name in another table using nested eager loading with eloquent and laravel

So I currently have 3 models Specie Type User. I want to be able to get the name of the last modified user in relation to the Specie model

The relationships are as follows

Class Specie extends Model {
   public function type()
   {
        return $this->belongsTo('App\Type', 'type_id');
   }

   public function user()
   {
        return $this->belongsTo('App\User', 'user_id');
   }
}

Class Type extends Model {
   public function specie()
   {
        return $this->hasMany('App\Specie', 'type_id');
   }
}

Class User extends Model {
   public function specie()
   {
        return $this->hasMany('App\Specie', 'user_id');
   }
}

I have tried this

Class Specie extends Model {
    public function lastModified()
    {
        return $this->belongsTo('App\User', 'last_modified_by');
    }
}

And then used the below code

$this->type->with(['specie.lastModified' => function ($query) use 
        ($userId) {
            $query->where('user_id', $userId);
        }])->get();

Unfortunately this does not seem to work

However, by using this code

$this->type->with(['specie' => function ($query) use ($userId) {
            $query->where('user_id', $userId);
        }])->get();

I am able to get this:

"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
  {
    "id": 6,
    "user_id": 1,
    "type_id": 1,
    "note": "et",
    "last_modified_by": 1,
  },
  {
    "id": 7,
    "user_id": 1,
    "type_id": 2,
    "note": "sa",
    "last_modified_by": 2,
  },
]

However, what I want to get is the name of the last modified person name which is the primary key in the User model and the foreign key in the Specie model

This is what I expect to get:

"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
  {
    "id": 6,
    "user_id": 1,
    "type_id": 1,
    "note": "et",
    "last_modified_by": 1,
    "user": [
        {
         "id": 1,
         "user": 'gerrard'
        }
    ]
  },
  {
    "id": 7,
    "user_id": 1,
    "type_id": 2,
    "note": "sa",
    "last_modified_by": 2,
    "user": [
         {
           "id": 2,
           "user": 'chris'
         }
    ]
  }
]



via Chebli Mohamed

Laravel cart - button and cart update

On the products page the button click links to add to cart page with the product id shown in the url however on the add to cart page the cart still shows no items in cart. Also the if statement relating to the session also doesn't appear to be working. So the problem is the cart is not updating.


                          <a href=""
                                   class="btn btn-success pull-right" role="button">Add to Cart</a>
                                @if(Session::has('success'))
       <div class="row">
          <div class="col-sm-6 col-md-4 col-md-offset-4 col-sm-offset-3">
                <div id="charge-message" class="alert alert-success">
                    
                   @endif

   ```shopping cart               

@if(Session::has('cart'))

        <div class="row">
            <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
                <ul class="list-group">
                   @foreach ((object)$products as $product)
                            <li class="list-group-item">
                                <span class="badge"></span>
                                <strong></strong>
                                <span class="label label-success"></span>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-primary btn-xs dropdown-toogle" data-toggle="dropdown">Action <span class="caret"></span></button>
                                    <ul class="dropdown-menu">
                                        <li><a href="">Reduce by 1</a></li>
                                        <li><a href="">Reduce All</a></li>
                                    </ul>
                                </div>
                            </li>
                     @endforeach
                </ul>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
                <strong>Total: </strong>
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-sm-6 col-md-6 col-md-offset-3 col-sm-offset-3">
                <a href="" type="button" class="btn btn-success">Checkout</a>
            </div>
        </div>





via Chebli Mohamed

Laravel sign in

I can sign up to the database but can't use info from the database to successfully login.

 public function getSignin()
    {
        return view('user.signin');
    }
    public function postSignin(Request $request)
    {
        $this->validate($request, [
            'email' => 'email|required',
            'password' => 'required|min:4'
        ]);
 if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
            return redirect()->route('user.profile');
        }
        return redirect()->back();

    }



via Chebli Mohamed

The route cant get the id from the form (Missing required parameters for [Route: update_user])

When i go to the page:blog.local/user/1 it returns this error:

Missing required parameters for [Route: update_user] [URI: user/{user}/update]. (View: C:\xampp\htdocs\blog\resources\views\login_pages\user.blade.php)

This is the view user.blade.php:

<h2 class="mypositionclass" > welcome user: </h2>
<hr>

<div style="text-align: center" >
    
    <div>
        <br>
        
    </div>
    <div>
        <br>
        
    </div>
    <div>
        <br>
        
    </div>
    <div>
        <br>
        
    </div>
    <div>
        <br><br>
        
    </div>
</div>

This is the route:

Route::post('/user/{user}/update', 'Login_pageController@update')->name('update_user');

This is the function update() from Login_pageController.php:

public function update(Request $request, $id)
{
    $request::validate([
        'name'=>'required',
        'surname'=>'required',
        'email'=>'required',
        'password'=>'required'
    ]);

    $user=User::findOrFail($id);
    $user->name= $request->name;
    $user->surname= $request->surname;
    $user->email= $request->email;
    $user->password= $request->password;
    $user->save();
    return view('login_pages.login_page');
}



via Chebli Mohamed

Call to undefined method Illuminate\Database\Query\Builder::unique()

I'm using database Query Builder in Laravel (5.5.46). In my database, one column has not unique values, so I want all the values from that column should be distinct or unique.

I used distinct() method but it discarded my repeated value. So I used unique() function. But I got this error.

$job_data = \DB::table('jobs')
                   ->orderBy('created_at', 'desc')
                   ->unique('job_id')->paginate(10);

In database {1,1,2,3,4,2}

I expect {1,2,3,4} but I got this error

BadMethodCallException

Call to undefined method Illuminate\Database\Query\Builder::unique()



via Chebli Mohamed

impossible to add, a recording

I'm trying to add a recording in my form Revision, but it misses a few things? I can add a recording via phpmyadmin but not on my form.

create.revision

enter image description here

index.revision

enter image description here

Here is, below my function store():

public function store(revisionRequest $request)
    {

        $date_revision_start = $request->get('date_revision_start');
        $date_revision_end = $request->get('date_revision_end');
        $garage = $request->get('garage');
        $fk_motorbike = $request->get('fk_motorbike');



        $conflict = Revision::whereDate('fk_motorbike', $request->get('fk_motorbike'))->whereDate('date_revision_start', "<=" , $date_revision_start);

        $conflict2 = Revision::whereDate('fk_motorbike', $request->get('fk_motorbike'))->whereDate('date_revision_start', "<=" , $date_revision_end)->whereDate('date_revision_end', ">=", $date_revision_end)->first();
        dd($conflict);

        if(isset($conflict2) || isset($conflict)){
            return redirect()->route('revisions.index')
             ->with('error', 'duplicate');
        }


       else{
        Revision::create($request->all());
            return redirect()->route('revisions.index')
                ->with('success', 'new data created successfully');
        }

    }

I don't understand the error ???

enter image description here

I thank you in advance for your help.



via Chebli Mohamed

Laravel Accessor or HasManyThrough or something else?

I have four models: User, Product, Order, OrderItem

When a User adds an item to his cart, it creates a new Order and the item becomes a new OrderItem.

The tables:

users
    id - integer
    name - string

products
    id - integer
    name - string

orders
    id - integer
    user_id - integer
    paid - boolean

order_items
    order_id - integer
    product_id - integer
    quantity -integer
    price - double

Relationships:

`Product` hasMany `OrderItem`
`OrderItem` belongsTo `Order`
`OrderItem` belongsTo `Product`
`Order` hasMany `OrderItem`
`User` hasMany `Order`

I want to be able to list all Product and under each, all the Users who bought that Product (Order whereNotNull 'paid'). Inversely, I'd like to show a User all the Products they have purchased.

I've tried taking it in steps with relationships. I can get to work, but not

Laravel doesn't allow hasManyThrough relationships with a pivot table, which is essentially what order_items is, so that won't work.

Maybe I could do this with an Accessor with a join, but I can't wrap my head around it because I can't really set the relationship.



via Chebli Mohamed

I want to pass two parameters to the URL

I want to pass two parameters with the route helper
One is the thread ID and the other is less so I want to pass both

index.blade.php

@foreach($works as $work)
<tr>
<td><a href=""></a></td>

web.php

Route::get('/work/edit/{id}/{project}', 'WorkController@edit')->name('work.edit');

Incidentally, the error appears like this

Missing required parameters for [Route: work.edit] [URI: work/edit/{id}/{project}]. 

I don't have a good idea of ​​what to do



via Chebli Mohamed

How to get is user like comment or not via Laravel Relationship?

i have post and post have comments and comments have likes i want to know that is login user like comment or not via Relationship

In controller i return post with comments

return $posts = Post::with('comments')->paginate(3);

In Post Model

public function comments()
    {
        return $this->hasMany('App\Models\Comment','post_id')
                ->where('parent_id',0)
                ->with('user','subComments','like')
                ->orderBy('id', 'desc');
    }


In Comments Model

public function like() 
    { 
        return $this->HasMany('App\Models\CommentLike');

    }


    public function subComments()
    {
       return $this->hasMany('App\Models\Comment', 'parent_id')->with('user','like');
    }




via Chebli Mohamed

How to set custom middlewares in Vue.js

I've been working on a college project by Laravel & Vue.js. I'm almost new in Vue.js.

I've idea about laravel middleware, but in my project, I want to make and set custom middlewares with combination with vue-router and vuex. For example auth & guest middleware as basics & If I additionally create any middleware, that should work also, I've not found any docs about middleware in vue.js docs.

Here's my store/auth module:

import axios from 'axios'
import Cookies from 'js-cookie'
import * as types from '../mutation-types'

// state
export const state = {
    user: null,
    token: Cookies.get('token')
}

// getters
export const getters = {
    user: state => state.user,
    token: state => state.token,
    check: state => state.user !== null
}

// mutations
export const mutations = {
    [types.SAVE_TOKEN] (state, { token, remember }) {
        state.token = token
        Cookies.set('token', token, { expires: remember ? 365 : null })
    },

    [types.FETCH_USER_SUCCESS] (state, { user }) {
        state.user = user
    },

    [types.FETCH_USER_FAILURE] (state) {
        state.token = null
        Cookies.remove('token')
    },

    [types.LOGOUT] (state) {
        state.user = null
        state.token = null

        Cookies.remove('token')
    },

    [types.UPDATE_USER] (state, { user }) {
        state.user = user
    }
}

// actions
export const actions = {
    saveToken ({ commit, dispatch }, payload) {
        commit(types.SAVE_TOKEN, payload)
    },

    async fetchUser ({ commit }) {
        try {
            const { data } = await axios.get('/api/user')
            commit(types.FETCH_USER_SUCCESS, { user: data })
        } catch (e) {
            commit(types.FETCH_USER_FAILURE)
        }
    },

    updateUser ({ commit }, payload) {
        commit(types.UPDATE_USER, payload)
    },

    async logout ({ commit }) {
        try {
            await axios.post('/api/logout')
        } catch (e) { }

        commit(types.LOGOUT)
    },

    async fetchOauthUrl (ctx, { provider }) {
        const { data } = await axios.post(`/api/oauth/${provider}`)
        return data.url
    }
}

How can I create and call middleware in vue template.

Please suggest if store/auth should have any changes!



via Chebli Mohamed

facing Trying to get property 'name' of non-object problem can't solved it

When i am want to show my employee profile and want to add department and designation from another table i am facing this problem. I can't solved it..i saw previous question but can't solved my answers.

Controller:

public function show($id)
{
    $data['title'] = "Profile";
    $data['employee'] = Employee::with(['department','designation'])->findOrFail($id);
    $data['departments'] = Department::orderBy('name')->pluck('name','id');
    $data['designations'] = Designation::orderBy('name')->pluck('name','id');
    return view('admin.employee.show',$data);
}

view:

<li>
  <div class="title">Department:</div>
  <div class="text"></div>
</li>

Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;

class Employee extends Model
{
    use SoftDeletes;
    use Notifiable;
    protected $fillable = [
        'firstname','lastname', 'email', 'password','designation_id','department_id'];

    public function designation()
    {
        return $this->belongsTo(Designation::class);
    }
    public function department()
    {
        return $this->belongsTo(Department::class);
    }
}

Trying to get property 'name' of non-object (View: C:\xampp\htdocs\hrm\resources\views\admin\employee\show.blade.php)



via Chebli Mohamed

vendredi 30 août 2019

anchor tag is not properly working in my Laravel site

In my Laravel site I want to link up my facebook account with the website but it is not working properly. If I am using

<a href=""></a>

for that, link shown like this

https://myDomainName/www.facebook.com/my_fb_page_id

But if I want to show only the facebook link with my fb id, for that I have used

<a href="www.facebook.com/my_fb_page_id"></a>

For that also the link shown same like below

https://myDomainName/www.facebook.com/my_fb_page_id

Where is my fault. Can't figure it out.

Anybody help please ? Thanks in advance.



via Chebli Mohamed

laradock cannot migrate table

Hi can I ask some help I have fresh copy of laravel "laravel/framework": "5.8.*", and also the laradock fresh also. my problem is that when trying to access php artisan migrate I get error

root@e6cc582a58d8:/var/www# php artisan migrate

Illuminate\Database\QueryException : SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client (SQL: select * from information_schema.tables where table_schema = smrf and table_name = migrations and table_type = 'BASE TABLE')

at /var/www/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664 660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) {

664| throw new QueryException( 665| $query, $this->prepareBindings($bindings), $e 666| ); 667| } 668|

Exception trace:

1 PDOException::("PDO::__construct(): The server requested authentication method unknown to the client [caching_sha2_password]") /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

2 PDO::__construct("mysql:host=mysql;port=3306;dbname=mydbname", "root", "mypassword", []) /var/www/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70

Please use the argument -v to see more details. root@e6cc582a58d8:/var/www# php artisan migrate

but in my sqleditor client I can connect host:mysql username:root password:root

Laravel.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydbname
DB_USERNAME=root
DB_PASSWORD=mypassword

laradock.env

### MYSQL #################################################

MYSQL_VERSION=latest
MYSQL_DATABASE=default
MYSQL_USER=default
MYSQL_PASSWORD=secret
MYSQL_PORT=3306
MYSQL_ROOT_PASSWORD=root
MYSQL_ENTRYPOINT_INITDB=./mysql/docker-entrypoint-initdb.d

laradock\docker-compose.yml

### MySQL ################################################
    mysql:
      build:
        context: ./mysql
        args:
          - MYSQL_VERSION=${MYSQL_VERSION}
      environment:
        - MYSQL_DATABASE=${MYSQL_DATABASE}
        - MYSQL_USER=${MYSQL_USER}
        - MYSQL_PASSWORD=${MYSQL_PASSWORD}
        - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
        - TZ=${WORKSPACE_TIMEZONE}
      volumes:
        - ${DATA_PATH_HOST}/mysql:/var/lib/mysql
        - ${MYSQL_ENTRYPOINT_INITDB}:/docker-entrypoint-initdb.d
      ports:
        - "${MYSQL_PORT}:3306"
      networks:
        - backend

DB_PASSWORD=mynewpass



via Chebli Mohamed

How to get foreign key name of loaded relationship using laravel eloquent

So I currently have 3 models Specie Type User. I want to be able to get the name of the last modified user in relation to the Specie model

The relationships are as follows

Class Specie extends Model {
   public function type()
   {
        return $this->belongsTo('App\Type', 'type_id');
   }

   public function user()
   {
        return $this->belongsTo('App\User', 'user_id');
   }
}

Class Type extends Model {
   public function specie()
   {
        return $this->hasMany('App\Specie', 'type_id');
   }
}

Class User extends Model {
   public function specie()
   {
        return $this->hasMany('App\Specie', 'user_id');
   }
}

I have tried this

Class Specie extends Model {
    public function lastModified()
    {
        return $this->belongsTo('App\User', 'last_modified_by');
    }
}

And then used the below code

$this->type->with(['specie.lastModified' => function ($query) use 
        ($userId) {
            $query->where('user_id', $userId);
        }])->get();

Unfortunately this does not seem to work

However, by using this code

$this->type->with(['specie' => function ($query) use ($userId) {
            $query->where('user_id', $userId);
        }])->get();

I am able to get this:

"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
  {
    "id": 5,
    "user_id": 1,
    "type_id": 1,
    "note": "et",
    "created_by": 1,
    "last_modified_by": 1,
  }
]

However, what I want to get is the name of the last modified person name which is the primary key in the User model and the foreign key in the Specie model

This is what I expect to get:

"id": 1,
"type": "Halo",
"created_at": "2019-07-20 13:02:53",
"updated_at": "2019-07-20 13:02:53",
"specie": [
  {
    "id": 5,
    "user_id": 1,
    "type_id": 1,
    "note": "et",
    "created_by": 1,
    "last_modified_by": 1,
    "last_modified_name": 'gerrard'
  }
]



via Chebli Mohamed

I downloaded a project from server but the images are not showing with correct path

I downloaded a project from server, it's using part Laravel + part plain HTML. The image tag below :-

<a href=""><img id="header-logo-image" src="" />

When I inspect element on the image and right click , open image in new tab, I get http://localhost/project1/files/logo/logo.png It shows object not found.

However if I open a new tab in the browser, and put in the URL http://localhost/project1/files/logo/logo.png , the image appears.

Any advise why it's not appearing when view from the project? Thanks



via Chebli Mohamed

set a due date dynamic

I would like to set a due date (dynamic), the person can register if it is 17to 60 years old.

I have tried this:

'date_naissance' => 'required|date|after:1960|before:2003-01-01'

But, I have to change the values each years.It is possible to improve this?

Thank you



via Chebli Mohamed

The dates and checking for a planning

I have a problem concerning the checking of my dates.

Example, my motorbike number 000001 is in revision from 30/08/2019 to 03/09/2019. The recording is good. (no problem)

However, if I add a revision on 02/09/2019 to 03/09/2019, I would like to add an error message explaining that the motorbike is already in revision.

enter image description here

My function index() is like this:

$revisionId = Revision::whereDate('date_revision_start', "<=" , $now)
->whereDate('date_revision_end', ">=", $now)
->pluck('fk_motorbike')->toArray();

I think my problem is in my function store()???

public function store(Request $request)
    {      

       $exists = Motorbike::where('matriculation', $request->get('matriculation'))->where('number_motorbike', $request->get('number_motorbike'))->where('status', $request->get('status'))->count();

       if (!$exists){

        $revisions = Revision::??????

        if (!$exists){
            Motorbike::create($request->all());
            return redirect()->route('motorbikes.index')
                ->with('success', 'new data created successfully');
        }

        else{
            return redirect()->route('motorbikes.index')
                 ->with('error', 'duplicate');

        }   

    }

    }

Class Motorbike

class Motorbike extends Model
{
    //
    protected $fillable = ['matriculation', 'number_motorbike', 'status'];
    etc...

Class Revision

class Revision extends Model
{
    //
    protected $fillable = ['date_revision_start', 'date_revision_end', 'garage', 'fk_motorbike'];

Thank you for your help



via Chebli Mohamed

Why won't my Laravel 5.2 events queue to Redis?

Locally, my Laravel 5.2 project works well, including events that are queued using Redis.

But I've deployed my project to a production server (where I'm using a Laradock Docker setup).

There, on production, Redis works for caching and for delayed dispatching of jobs.

So I know that my Redis setup is good.

But events don't work (even though they worked when my project was on my local computer).

My question is not a duplicate of Laravel 5.2 event not firing in production because I'm not using broadcasting and because I am using Laradock.

I've also already tried these commands (inside the container at docker exec -it laradock_workspace_1 bash):

php artisan config:cache
php artisan clear-compiled
php artisan optimize
composer install --no-dev
composer dumpautoload
php artisan queue:restart



via Chebli Mohamed

does laravel do some process with the data returned in controllers before send?

I have a issue with the response time when load a lot of information (laravel models) with some relations, i am debugging, and the process of get the data from database take a litle bit of time, but when the response of controller is sent, it take more time and i dont know what is the problem, im doing some wrong?

First I thought that sending a lot of data in response could generate an increase in time, so I leaked the data and sent only what was necessary, this improved the time, but only a few seconds,

        $start = microtime(true);

        $current_user = $this->getCurrentUser();

        //Getting data from database
        $data = myFunction($current_user);

        $time_elapsed_secs = microtime(true) - $start;
        dd($time_elapsed_secs); //logs 2 seconds;

        return data; // but when i return data, it takes about 50 seconds 
                       in reaching the browser



via Chebli Mohamed

Eloquent model - relationship user category and account handling

I have a particular scenario whereby a user can belong to another user, a group or a service provider.

For eg. a Company (is a user/service provider) has a client (also a user) and a client may have member (group of users) and a group of users ( as per membership modal).

What is the best way to use eloquent model for such scenario.

Thanks in advance.

I have tried user role as per acedmind on youtube as below code.

class Role extends Model
{
//Roles Model
//relationship with users
public function users()
{
return $this->belongsToMany('App\User','user_role','role_id','user_id');
}
}

and in User
//Roles relationship
public function roles()`enter code here`
{
return $this->belongsToMany('App\Role','user_role','user_id','role_id');
}

public function hasAnyRole($roles)
{
  if(is_array($roles)){
 foreach ($roles as $role) {
   if ($this->hasRole($role)){
   return true;
 }
 }
 }else {
  if ($this->hasRole($roles)){
return true;
  }
}
 return false;
}

public function hasRole($role)
{
  if ($this->roles()->where('name',$role)->first()){
return true;
  }
  return false;
 }

  1. a User can be a service provider. (can belong to a group)
  2. a user can be a client as individual and/or can belong to a group
  3. a group can have types of service provider or a client
  4. a service provider has investigation records for each client which will be reviewed as an individual or a group.


via Chebli Mohamed

Laravel jwt authentication for admin dashboard

How to implement laravel jwt authentication using front end login,logout and registration, login,logout.

Please give me any suggestions.



via Chebli Mohamed

How to select specifics fields form HybridRelations in laravel?

Hi i have one model "Trip" with postgress connection and another model "ComponentValue" with mongodb connection

i have created a query to retrieve trips with component value like this

public function getVehicleTrips($vehicleID, $filters = null, $withPaginate = true)
{
    try {

        $query = Trip::query()
            ->where('vehicle_id', '=', $vehicleID)
            ->with('heightsDamagedComponentValue')
            ->with('lowestDamagedComponentValue')
            ->with('heightsDamagedComponentValue.componentType')
            ->with('lowestDamagedComponentValue.componentType');


        $query = $this->applyTripsDatesFilters($query, $filters);



        if ($withPaginate) {
            $query = $query->paginate(Helpers::getKeyValue($filters, 'limit', 10));

        }

        $query = $query->sortByDesc('heightsDamagedComponentValue.damage')->values();

        $result = $query;

        return $result;

    } catch (\Exception $e) {

        return false;
    }
}

the data are retrieved but the heightsDamagedComponentValue has some fileds that i don't want to include them in the result, even i don't want to be included in the query selection

so how i can specific some fields to retrieved from the mongo relationship heightsDamagedComponentValue ?

i already tried this solution and tried to add

 protected $guarded = ['id', 'data'];

to the ComponentValue model but it didn't work also,

the heightsDamagedComponentValue method is

public function heightsDamagedComponentValue()
{
    return $this->hasOne(ComponentValue::class)->orderBy('damage', 'desc');
}

please any help and many thanks in advance



via Chebli Mohamed

How to get country code from object in php?

I am beginner in php/laravel.

I have array with objects

This is sample object:

Geocoder\Provider\Nominatim\Model\NominatimAddress Object
(
    [attribution:Geocoder\Provider\Nominatim\Model\NominatimAddress:private] => Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright
    [category:Geocoder\Provider\Nominatim\Model\NominatimAddress:private] => boundary
    [displayName:Geocoder\Provider\Nominatim\Model\NominatimAddress:private] => Rumo, Comunità della Val di Non, TN, TAA, Italia
    [osmType:Geocoder\Provider\Nominatim\Model\NominatimAddress:private] => relation
    [osmId:Geocoder\Provider\Nominatim\Model\NominatimAddress:private] => 47201
    [type:Geocoder\Provider\Nominatim\Model\NominatimAddress:private] => administrative
    [coordinates:Geocoder\Model\Address:private] => Geocoder\Model\Coordinates Object
        (
            [latitude:Geocoder\Model\Coordinates:private] => 46.4610571
            [longitude:Geocoder\Model\Coordinates:private] => 10.9882457
        )

    [bounds:Geocoder\Model\Address:private] => Geocoder\Model\Bounds Object
        (
            [south:Geocoder\Model\Bounds:private] => 46.4218546
            [west:Geocoder\Model\Bounds:private] => 10.9308997
            [north:Geocoder\Model\Bounds:private] => 46.4840451
            [east:Geocoder\Model\Bounds:private] => 11.0481174
        )

    [streetNumber:Geocoder\Model\Address:private] => 
    [streetName:Geocoder\Model\Address:private] => 
    [subLocality:Geocoder\Model\Address:private] => 
    [locality:Geocoder\Model\Address:private] => Rumo
    [postalCode:Geocoder\Model\Address:private] => 
    [adminLevels:Geocoder\Model\Address:private] => Geocoder\Model\AdminLevelCollection Object
        (
            [adminLevels:Geocoder\Model\AdminLevelCollection:private] => Array
                (
                    [1] => Geocoder\Model\AdminLevel Object
                        (
                            [level:Geocoder\Model\AdminLevel:private] => 1
                            [name:Geocoder\Model\AdminLevel:private] => TAA
                            [code:Geocoder\Model\AdminLevel:private] => 
                        )

                    [2] => Geocoder\Model\AdminLevel Object
                        (
                            [level:Geocoder\Model\AdminLevel:private] => 2
                            [name:Geocoder\Model\AdminLevel:private] => Comunità della Val di Non
                            [code:Geocoder\Model\AdminLevel:private] => 
                        )

                )

        )

    [country:Geocoder\Model\Address:private] => Geocoder\Model\Country Object
        (
            [name:Geocoder\Model\Country:private] => Italia
            [code:Geocoder\Model\Country:private] => IT
        )

    [timezone:Geocoder\Model\Address:private] => 
    [providedBy:Geocoder\Model\Address:private] => nominatim
)

My php code:

foreach (app('geocoder')->geocode($request->input('city'))->get() as $key => $value) {
            //echo $value->country->code;
            echo"<pre>"; print_r($value); echo"</pre>";
        }

I want check country code. If country->code == PL - then I hand show text: "It's correct" or if not - then I want show text "wrong".

How can I make it?

I need result:

It's correct
It's correct
It's correct
wrong
It's correct

etc

How can I make it?



via Chebli Mohamed

Add an all views wilcard to view composers from within a laravel package

I have a view composer working from within a package for a specific directory:

$view->composer(
        'cms::admin.*', ProfileComposer::class
    );

But I also have view composers that should be loaded across all root views, however the following are not being loaded as required:

$view->composer(
            'cms::*', NavigationComposer::class
        );

        $view->composer(
            'cms::*', SiteConfigComposer::class
        );

Any idea how to apply these view composers to all routes?



via Chebli Mohamed

Get controller and action of route in Laravel

I want to resolve the controller name and action which are configured for a route

I have a route:

Route::get('/somePage','SomeController@someAction');

Can I get the controller name and action using something like:

resolve('/somepage');

to receive the same result which I can get from Route::current()->getActionName()

App\Http\Controllers\SomeController@someAction



via Chebli Mohamed

Create Laravel Package but Command not Listed On Artisan

I've been create simple package here is the structure of my directory

├── composer.json
└── src
    ├── ArtisanTestmeServiceProvider.php
    └── Commands
        └── TestmeCommand.php

my problem is, my custom command not listed on artisan (php artisan)

here is the source code of TestMeCommand.php

<?php

namespace TestMe\Commands;

use Illuminate\Console\Command;

class TestmeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'testme:run';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'lorem ipsum';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $this->info("Version : test test");
    }
}

and here is the ServiceProvider ArtisanTestmeServiceProvider

<?php

namespace TestMe\Commands;

use Illuminate\Support\ServiceProvider;

class ArtisanTestmeServiceProvider extends ServiceProvider
{
    protected $commands = [
        'robyfirnandoyusuf\TestMe\Commands\TestmeCommand',
    ];


    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->commands($this->commands);
    }
}

and below is composer.json in my package

{
    "name": "robyfirnandoyusuf/lara-testme",
    "description": "test",
    "license": "MIT",
    "authors": [
        {
            "name": "Roby Firnando Yusuf",
            "email": "idonthave@gmail.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload" : {
        "psr-4":{
            "TestMe\\": "src/"
        }
    },
    "extra":{
        "laravel":{
            "providers":[
                "TestMe\\Commands\\ArtisanTestmeServiceProvider"
            ]
        }
    }
}

and at composer.json on laravel project , I've been added :

 "repositories":[
        {
            "type": "path",
            "url": "../Packagistku/TestPackage/"
        }
    ],

Am I miss something so that my custom command not listed on artisan command ?



via Chebli Mohamed

How can I register a View::composer from a Laravel package?

How can I register a View::composer for use in a Laravel project from within a Laravel package?

In my package service provider I have a boot method with routes/views etc and this in the register function:

public function register()
    {

        $this->app->register(ComposerServiceProvider::class); 
    }

In the ComposerServiceProvider I have:

   public function boot()
    {
        View::composer(
            'admin.*', ProfileComposer::class
        );
    }

Which should load the ProfileComposer class into all admin.* views, but it's not working. I can't see anything in the Laravel documentation regarding loading View Composers from packages

This code has been extracted from my working laravel project for use as a package going forward but the view composers are causing issues



via Chebli Mohamed

Want to display the canvas image in my laravel project with in the @section tag

I just want to display the canvas image in my laravel project.

I had already tried the canvas in separate files like Html and PHP files the canvas is working but when I am trying to show the canvas image in my laravel project total image is not displaying.

    @section('content-wrapper')
<canvas id="canvas" width="484" height="984"></canvas>
@endsection
            @push('scripts')
            <script src="https://www.marvinj.org/releases/marvinj-0.8.js"></script>
        <script>
            var canvas = document.getElementById("canvas");
            image1 = new MarvinImage();
            image1.load("packages/Webkul/Shop/src/Resources/assets/images/Group 1.png", imageLoaded);
            image2 = new MarvinImage();
            image2.load("packages/Webkul/Shop/src/Resources/assets/images/Rectangle 5.png", imageLoaded);
            image3 = new MarvinImage();
            image3.load("packages/Webkul/Shop/src/Resources/assets/images/Motif_2.png", imageLoaded);
            image4 = new MarvinImage();
            image4.load("packages/Webkul/Shop/src/Resources/assets/images/body_design_2.png", imageLoaded);

            var loaded=0;



            function imageLoaded(){
              if(++loaded == 4){
                var image = new MarvinImage(image1.getWidth(), image1.getHeight());
                Marvin.combineByAlpha(image1, image2, image, 43, 0);
                Marvin.combineByAlpha(image, image3, image, 0, 0);
                Marvin.combineByAlpha(image, image4, image, 50, 0);
                image.draw(canvas);
              }
            }

        </script>
        @endpush

Just want to display the canvas in my laravel project.



via Chebli Mohamed

Why font awesome icons are not coming in live?

http://nafidev.com/auth/public/

Where I put my Project in above link.

Laravel 5.7 + Font Awesome

Tried to solve following SO answer, But not wokring.

Which file need to give here please tell me I will paste it.



via Chebli Mohamed

URL not encoding correctly from Laravel Job

Using guzzle in laravel 5.8 to make external API requests in my app. When I perform a request from a controller it works fine.

How ever when using the same code in a Job which I dispatch in a controller, I dont get the same results, I get an incorrect url.

Tried using a variety of url and utf8 encoding/decoding

$name = 'Cheeríos';
$this->httpClient->get("$baseUri/" . strtolower($name) . "/info")->getBody();

actual results of url, which leads to a 404 because its removed the í from the name

example.com/user/cheer%E3%ADos/info

expected

example.com/user/cheer%C3%ADos/info
or
example.com/user/cheeríos/info



via Chebli Mohamed

The column exists but cannot be saved

The column exists but cannot be saved
index.blade.php

<form action="" method="post">
@csrf
<input type="hidden" name="project_id" value="">

WorkController.php

public function store(Request $request,$id)
{
    $work = new Work;
    $work->fill($request->all())->save();
    return redirect()->route('workindex', ['id' => $id]);
}

create_work_table.php

    Schema::create('work', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('project_id');
        $table->text('content');
        $table->integer('user_id');
        $table->time('work_time');
        $table->string('input_person');
        $table->timestamp('input_date');

        $table->softDeletes();
        $table->timestamps();
    });

web.php

Route::post('/work/{id}', 'WorkController@store')->name('work.store');

Exists but does not exist

SQLSTATE[HY000]: General error: 1 table category has no column named project_id (SQL: insert into "category"



via Chebli Mohamed

How to update Laravel composer.json

I included "tymon/jwt-auth" : "~1.0.0-rc.2" in my composer.json file. and when i run composer update, it returns the following errors: Cannot create cache directory /home/mpete/.composer/cache/repo/https---packagist.org/, or directory is not writable. Proceeding without cache Cannot create cache directory /home/mpete/.composer/cache/files/, or directory is not writable. Proceeding without cache

"require": { "php": "^7.1.3", "fideloper/proxy": "^4.0", "laravel/framework": "5.8.*", "laravel/tinker": "^1.0", "tymon/jwt-auth" : "~1.0.0-rc.2" }enter image description here



via Chebli Mohamed

jeudi 29 août 2019

Function return error: Incorrect APP1 Exif Identifier Code

I am beginner in Laravel and Php. In my project I use Laravel 5.8 and PHP 7.2. I have this code:

function correctImageOrientation($filename)
{
    if (function_exists('exif_read_data')) {
        $exif = exif_read_data($filename);
        if ($exif && isset($exif['Orientation'])) {
            $orientation = $exif['Orientation'];
            if ($orientation != 1) {
                $img = imagecreatefromjpeg($filename);
                $deg = 0;
                switch ($orientation) {
                    case 3:
                        $deg = 180;
                        break;
                    case 6:
                        $deg = 270;
                        break;
                    case 8:
                        $deg = 90;
                        break;
                }
                if ($deg) {
                    $img = imagerotate($img, $deg, 0);
                }
                imagejpeg($img, $filename, 95);
            }
        }
    }
}

and sometimes I have this error:

[2019-08-30 08:23:29] public.ERROR: exif_read_data(87db75b052e7a9f1edfbbe9b5d9defca.jpg): Incorrect APP1 Exif Identifier Code {"userId":3,"exception":"[object] (ErrorException(code: 0): exif_read_data(87db75b052e7a9f1edfbbe9b5d9defca.jpg): Incorrect APP1 Exif Identifier Code at /usr/home/name/domains/name.com/correctImageOrientation.php:6)

How can I repair it? Maybe its possible add something like "try"?



via Chebli Mohamed

I wrote a csrf tag, but somehow 419 came back

I am writing @csrf but getting 419 error

index.blade.php

<form action="" method="post">
@csrf
<input type="hidden" name="id" value="">
<label for="input">InputPerson</label>
<select name="user_name">
    @foreach($users as $user)
    <option value=""></option>
    @endforeach
</select>

web.php

Route::post('/work/{id}', 'WorkController@store')->name('work.store');

I should be able to save without 419 error but it is not happening



via Chebli Mohamed

Norifications:: not passing the specific data but working with array

i have a problem in Notification send email i cant get the specific data

when i tried to get the data specific like $this->equipment->id its not working but if i used $this->equipment it will display the array data

in my controller

        $equipment = Equipment::where('id','1')->get();
        Notification::send($users, new Equipment($equipment));

in my Notification
``<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

class Equipment extends Notification
{
    use Queueable;
    public $equipment;

    public function __construct($equipment)
    {
        $this->equipment = $equipment;
    }


    public function via($notifiable)
    {
        return ['mail'];
    }


    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line($this->equipment->id.'The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }


    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}


$this->equipment is working 
but $this->equipment->id is not working



via Chebli Mohamed

how can i pass custom message to blade from controller

i have this in my blade

 <input id="name" type="text"
                           class="form-control @error('name') is-invalid @enderror" name="name"
                           value="" autocomplete="name" autofocus>
                     @error('name')
                       <span class="invalid-feedback" role="alert">
                            <strong></strong>
                       </span>
                    @enderror

and i would like to pass this through my controller

 catch (\Exception $e){
 return back()->withError('name','Somthing Went Wrong Please Try Again!');
                }

but it does not work how can i fix this



via Chebli Mohamed

laravel 5.7 how to update datetime field to null

■ Laravel : 5.7

■ PHP : 7.2

I need to update model DateTime Field to null, but I don't know why when I input to null will update Field to current date time.

When I set form job_start or job_end on blank, than will update Field to current date time.

Also, I already have try $job->job_start = null; $job->save(); but get same result.

/?php

class Job extends Model {
/**
 * @var $casts(toArray、toJson)
 */
protected $casts = [
    'visit_date' => 'date:Y-m-d',
    'job_start' => 'datetime:Y-m-d H:i',
    'job_end' => 'datetime:Y-m-d H:i',
];

/**
 * @var date 
 */
protected $dates = [
    'visit_date', 
    'job_start',
    'job_end',
];

// $fillable(save、update、fill)
protected $fillable = [
    /**SKIP**/
    'visit_date', 
    'job_start',
    'job_end',
    /**SKIP**/
];

/**SKIP other function**/

/**
 * job_start
 * @param  string  $value ($value format 'Y:m:d H:i')
 * @return void
 */
public function setJobStartAttribute($value) {
    if($value !== null){
        //$value format 'Y:m:d H:i' to 'Y-m-d H:i:s'
        $value = (new Carbon($value))->format('Y-m-d H:i:s');
    }
    //set
    $this->attributes['job_start'] = $value;
}

/**
 * job_start
 * @param  string  $value ($value format 'Y:m:d H:i:s')
 * @return void
 */
public function getJobStartAttribute($value) {
        //$value format 'Y:m:d H:i:s' to 'Y-m-d H:i'
    return (new Carbon($value))->format('Y-m-d H:i');
}


}



via Chebli Mohamed

Planning on Laravel?

I have a table named "Motorbike" with as fields (matriculation', 'number_motorbike', 'status').

I have another table named "Revision" with as fields ('date_revision_start', 'date_revision_end', 'garage', 'fk_motorbike').

The goal is that if the motorbike is under revision, it must be unavailable (automatically)...

it works almost ! So, the modificaiton of the status for the motorbike changes automatically only for the date "today"

enter image description here

enter image description here

But, for the date from 02/08/2019 to 06/08/2019 I have a problem. When, we will be, on 02/08/2019 or 06/08/2019 the status of the motorbike is always available... Normally, it must be unavailable.

Can you help me solve this problem?

$motorbikes = Motorbike::oldest()->paginate(5);
$revisionId = Revision::where('date_revision_start', "<=" , Carbon::now())->where('date_revision_end', ">=", Carbon::now())->pluck('fk_motorbike')->toArray();

Thank you for your help.



via Chebli Mohamed

Save a model with multiple relationships with dynamically added childrens

I have a problem trying to save a model with relationships where has dynamically add children as follows.

   $RatesPlansRoom = RatesPlansRooms::find(113);
    $calendarys = $RatesPlansRoom->calendarys()->whereBetween(
        'date',
        ["2019-08-29" ,"2019-09-10"]
    )->with([
        'rate'
    ])->get();
    $RatesPlansRoom->setRelation('calendarys', $calendarys);
    foreach ($this->getDateRange() as $dateInput) {
        $dateRates = $RatesPlansRoom->calendarys->first(function ($item) use ($date) {
            return $item->date == $date;
        });

        if (empty($dateRates)) { // create
            $dateRates = new RatesPlansCalendarys();
            $dateRates->date = $date;

            $RatesPlansRoom->calendarys->add($dateRates);
        }

        foreach ($rates as $rateType => $ratesType) {
            foreach ($ratesType as $rate) {
                $rateSelected = $dateRates->rate->first(function ($value) use ($rateType, $rate) {
                    return $value->num_adult == $rate['num_adult'];
                });

                if (empty($rateSelected)) {// create
                    $rateSelected = new Rates();
                    $rateSelected->fill($rate);

                    $dateRates->rate->add($rateSelected);

                } else {
                    $rateSelected->fill($rate);
                }
            }
        }
    }

    $RatesPlansRoom->push();

Throw the following error

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (limatours_copia_pruebas.rates, CONSTRAINT rates_rates_plans_calendarys_id_foreign FOREIGN KEY (rates_plans_calendarys_id) REFERENCES rates_plans_calendarys (id)) (SQL: insert into rates (price_extra, updated_at, created_at) values (70, 2019-08-29 21:24:00, 2019-08-29 21:24:00))

It seems that in the relationship that must be created with

                $rateSelected = new Rates();
                $rateSelected->fill($rate);

                $dateRates->rate->add($rateSelected);

It is not filling the field "rates_plans_calendarys_id".



via Chebli Mohamed

How do I generate multiple pdf files

I want to generate several pdf files just by clicking on a button, but all the time, it's a single file that generates as the return statement stops the function.

Any help will be appreciated. Thanks

public function printPDF()
    {
        $fiches = FichePaiesInfos::where('user_id', Auth::user()->id)->get();

        foreach ($fiches as $fiche) {
            $data = [
                'name' => $fiche->personnelsInfos->name,
                'firstname' => $fiche->personnelsInfos->firstname,
                'fiche' => $fiche
            ];
            $pdf = PDF::loadView('layouts.pdf_view', $data);
        }
        return $pdf->download('fiche' . '_' . time() . '.pdf');;
    }



via Chebli Mohamed

Laravel hasOne vs belongsTo returns null

I'm quite new to Laravel and I'm trying to return values of two tables that have relationship, but I'm receiving null.

Here in my Controller I'm passing with('image').

$products = Produtos::select('codigo', 'descricao', 'CT', 'Fotos')->with('image')->take(2)->get();
return response()->json($products);

Image Model

class Objetos extends Model
{
    protected $table = 'Imagens';

    public function produtos(){
        return $this->belongsTo(\App\Produtos::class);
    }
}

Product Model

class Produtos extends Model
{
    public function image(){
        return $this->hasOne(\App\Objetos::class, 'Chave');
    }
}

The columns that have relationship are:

Objetos.Chave = Produtos.id

I can't see my error, but I think it's probably in the arguments I'm passing in hasOne and belongsTo.

Note: I'm accessing an external database (MS SQL), but I think it is not the problem.



via Chebli Mohamed

Laravel 5.5 task scheduler does not seem to be looping through all of my commands

I have a lot of cron tasks (below) which are supposed to be ran at various times. It does not seem to me that these tasks are all running... I run the command 'php artisan schedule:run' every minute set up on my forge server. My schedule function houses the following commands:

        $schedule->call(function () 
        {
            Log::info('SCHEDULER RAN AT: ' . Carbon::now());
        })->cron('* * * * *');
        $schedule->command('WelcomeMessages:send')->cron('* * * * *');

        $schedule->command('FirstDaySurveysEST:close')->cron('59 3 * * *');
        $schedule->command('FirstDaySurveysCST:close')->cron('59 4 * * *');
        $schedule->command('FirstDaySurveysPST:close')->cron('59 6 * * *');

        $schedule->command('DailySurveysEST:close')->cron('59 3 * * *');
        $schedule->command('DailySurveysCST:close')->cron('59 4 * * *');
        $schedule->command('DailySurveysPST:close')->cron('59 6 * * *');

        $schedule->command('DaysEST:add')->cron('0 4 * * *');
        $schedule->command('DaysCST:add')->cron('0 5 * * *');
        $schedule->command('DaysPST:add')->cron('0 7 * * *');

        $schedule->command('HelpSurveysEST:reset')->cron('1 4 * * *');
        $schedule->command('HelpSurveysCST:reset')->cron('1 5 * * *');
        $schedule->command('HelpSurveysPST:reset')->cron('1 7 * * *');

        $schedule->command('DailySurveysEST:reset')->cron('2 4 * * *');
        $schedule->command('DailySurveysCST:reset')->cron('2 5 * * *');
        $schedule->command('DailySurveysPST:reset')->cron('2 7 * * *');

        $schedule->command('DailySurveysEST:create')->cron('3 4 * * *');
        $schedule->command('DailySurveysCST:create')->cron('3 5 * * *');
        $schedule->command('DailySurveysPST:create')->cron('3 7 * * *');

        $schedule->command('PicSurveysEST:create')->cron('4 4 * * *');
        $schedule->command('PicSurveysCST:create')->cron('4 5 * * *');
        $schedule->command('PicSurveysPST:create')->cron('4 7 * * *');

        $schedule->command('TransitionSurveysEST:create')->cron('5 4 * * *');
        $schedule->command('TransitionSurveysCST:create')->cron('5 5 * * *');
        $schedule->command('TransitionSurveysPST:create')->cron('5 7 * * *');

        $schedule->command('PicSurveysEST:send')->cron('0 0 * * *');
        $schedule->command('PicSurveysCST:send')->cron('0 1 * * *');
        $schedule->command('PicSurveysPST:send')->cron('0 3 * * *');

        $schedule->command('DailySurveysEST:send')->cron('0 14 * * *');
        $schedule->command('DailySurveysCST:send')->cron('0 15 * * *');
        $schedule->command('DailySurveysPST:send')->cron('0 17 * * *');

        $schedule->command('TransitionSurveysEST:send')->cron('1 22 * * *');
        $schedule->command('TransitionSurveysCST:send')->cron('1 23 * * *');
        $schedule->command('TransitionSurveysPST:send')->cron('1 1 * * *');

        $schedule->command('TransitionRemindersEST:send')->cron('1 22 * * *');
        $schedule->command('TransitionRemindersCST:send')->cron('1 23 * * *');
        $schedule->command('TransitionRemindersPST:send')->cron('1 1 * * *');

        $schedule->command('RemindersEST:send')->cron('0 22 * * *');
        $schedule->command('RemindersCST:send')->cron('0 23 * * *');
        $schedule->command('RemindersPST:send')->cron('0 1 * * *');

        $schedule->command('Encouragement7EST:send')->cron('0 18 * * *');
        $schedule->command('Encouragement7CST:send')->cron('0 19 * * *');
        $schedule->command('Encouragement7PST:send')->cron('0 21 * * *');

        $schedule->command('Encouragement14EST:send')->cron('0 20 * * *');
        $schedule->command('Encouragement14CST:send')->cron('0 21 * * *');
        $schedule->command('Encouragement14PST:send')->cron('0 23 * * *');

        $schedule->command('Encouragement21EST:send')->cron('0 16 * * *');
        $schedule->command('Encouragement21CST:send')->cron('0 17 * * *');
        $schedule->command('Encouragement21PST:send')->cron('0 19 * * *');

        $schedule->command('Encouragement28EST:send')->cron('0 17 * * *');
        $schedule->command('Encouragement28CST:send')->cron('0 18 * * *');
        $schedule->command('Encouragement28PST:send')->cron('0 20 * * *');

        $schedule->command('Encouragement35EST:send')->cron('0 21 * * *');
        $schedule->command('Encouragement35CST:send')->cron('0 22 * * *');
        $schedule->command('Encouragement35PST:send')->cron('0 0 * * *');

Some of these commands are doubled up, so is that an issue?

All of these commands run through an array of the participants and then executes a function should they meet certain criteria... so the functions could take a bit and potentially run over top of each other...

I know that they pull the correct users. When I manually enter these functions they work as intended.

What could I be doing wrong?



via Chebli Mohamed

Laravel Loop through model children without repeating

How do you get all the model's children with ajax without getting the child repeatedly?

Currently, I pass the parent model on from the controller to the view like this:

    public function index($parent_id)
    {
        return view('view', ['parent' => Parent::findOrFail($parent_id)]);
    }

And then use the parent model to loop the children.

    @foreach($parent->children->shuffle() as @child)
        // Some code
    @endforeach

But this approach is has problem when the parent's children get up to 5,000 records. I'm thinking of fetching the children using ajax one by one or any other more efficient ways.



via Chebli Mohamed

Laravel Storage disks sftp

I want file from sftp disk to local

I configured my filesystems.php and appserviceprovider.php

Checking if exist works, but how can i put the remote file to my server?

$exists = Storage::disk('sftp')->exists(self::REMOTE_FILE_DEST);



via Chebli Mohamed

How to push the Laravel job to the queue

I have a class XYJob which was created by artisan command and implements the ShouldQueue class. The QUEUE_DRIVER=redis in the .env file.

The problem is that when i dispatch the job, it runs as a simple php function. The queue listener is not running, but the job runs as a simple function.

It is laravel 5.8 application with predis/predis: ^1.1. I have tried to clear the cache and the config. I have tried to use composer dump-autoload.

namespace Modules\ModuleName\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class XYJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \Log::info('Job is running');
    }
}

Laravel documentation says:

The generated class will implement the ShouldQueue interface, indicating to Laravel that the job should be pushed onto the queue to run asynchronously.

BUT my job is definitely running.



via Chebli Mohamed

Vue dropzone thumbnail is not showing after upload

I am making a system with laravel and vuejs . I am using vue dropzone for image upload process . the problem is my files are uploading on the server but i can not preview the thumbnail on my client side . I searched multiple times but didn't find any solution .

I have used basic demo from vue2-dropzone . But there i saw thumbnails are generating without any external function . i tried @vdropzone-complete="afterComplete" event and i could see the thumbnail details on the console afterComplete(file) { console.log(file); },

<vue-dropzone                                      
         ref="myVueDropzone"
         id="dropzone"
         @vdropzone-complete="afterComplete"
        :options="dropzoneOptions">
</vue-dropzone>
````````````````Here is my vue dropzone code
dropzoneOptions: {
                    url: '/api/photos/upload',
                    acceptedFiles: '.jpg,.jpeg,.png,.gif',
                    maxFiles: 6,
                    maxFilesize: 100,
                    addRemoveLinks: true,
                }
`````````````````Here is my laravel code for file upload
$objFile =    $request->file('file');
        $image =  time().$objFile->getClientOriginalName();
        @mkdir('image');
        $destinationPath = 'image';
        $objFile->move($destinationPath,$image);

Files are uploading on the server but i can not see them . Also is there any way to get the response from the server from vue upload so i can get the uploaded file names



via Chebli Mohamed

How to save multiple form dynamic data with single submit button without reload the page in laravel?

I want to save multiple form with one submit button, without refresh the page, however, I have done with the help of jquery and javascript. When submitting the data, it's showing error.

Here is controller

              public function store1(Request $request)
{
    $this->validate($request, [
        'title' =>'required',

        'event_video_link'=>'required',
        'event_place_name'=>'required',
        'speaker_name'=>'required',
        'speaker_position'=>'required',
        'event_session_name'=>'required',
        'session_person_name'=>'required',
        'session_person_topic'=>'required',

        'session_time'=>'required',
        'event_date'=>'required',


        'session_person_pdf'=>'mimes:jpeg,pdf,docx,png:5000',
        'Image'=>'mimes:jpeg,pdf,docx,png:5000',
        'Featured'=>'mimes:jpeg,pdf,docx,png:5000',
        'session_person_image'=>'mimes:jpeg,pdf,docx,png:5000',
        'category_id'=>'required',
    ]);



    // Create Initial Required Data Array
    $data = [
        'title'=>$request->title,
        'event_video_link'=>$request->event_video_link,
        'event_place_name'=>$request->event_place_name,
        'speaker_name'=>$request->speaker_name,
        'speaker_position'=>$request->speaker_position,
        'event_session_name'=>$request->event_session_name,
        'session_person_name'=>$request->session_person_name,
        'session_person_topic'=>$request->session_person_topic,



        'category_id'=>$request->category_id,
        'slug'=>str_slug($request->title),

        // $date = date('Y-m-d H:i:s'),
        //  $date_time = Carbon::createFromFormat('Y-m-d H:i:s', $date)
        // ->format('d-m-Y'),
        'session_time'=>Carbon::parse(strtotime($request->session_time))->format('Y-m-d'),
        'event_date'=>Carbon::parse(strtotime($request->event_date))->format('Y-m-d'),


    ];


    if($request->has('title'))
    {
        $data['title']=$request->title;
    }

    if($request->has('event_video_link'))
    {
        $data['event_video_link']=$request->event_video_link;
    }


    if($request->has('event_place_name'))
    {
        $data['event_place_name']=$request->event_place_name;
    }




    if($request->has('speaker_name'))
    {
        $data['speaker_name']=$request->speaker_name;
    }

    if($request->has('speaker_position'))
    {
        $data['speaker_position']=$request->speaker_position;
    }





    if($request->has('event_session_name'))
    {
        $data['event_session_name'] = $request->event_session_name;

    }

    if($request->has('session_person_name'))
    {
        $data['session_person_name'] = $request->session_person_name;

    }

    if($request->has('session_person_topic'))
    {
        $data['session_person_topic'] = $request->session_person_topic;

    }



    if (request('File'))
    {
        $File = request('File');
        $file_name = time() . $File->getClientOriginalName();
        $File->move('uploads/past', $file_name);
        $data['File'] = 'uploads/past/'.$file_name;
    }

    // Optionally add 'featured' if found to the Data array
    if (request('Featured'))
    {
        $Featured = request('Featured');
        $file_name = time() . $Featured->getClientOriginalName();
        $Featured->move('uploads/past', $file_name);
        $data['Featured'] = 'uploads/past/'.$file_name;
    }
    // Optionally add 'file' if found to the Data array
    if (request('Featured1')) {
        $Featured1 = request('Featured1');
        $file_name = time() . $Featured1->getClientOriginalName();
        $Featured1->move('uploads/past', $file_name);
        $data['Featured1'] = 'uploads/past/'.$file_name;
    }
    if (request('Image')) {
        $Image = request('Image');
        $file_name = time() . $Image->getClientOriginalName();
        $Image->move('uploads/past', $file_name);
        $data['Image'] = 'uploads/past/'.$file_name;
    }


    // Create the Post with the $data Array

    past_events::create($data);
    //$post=Post::whereBetween('created_at',[$date_time, $to])->get();
    Session::flash('success', 'New Blog has been Published on Website for 
    Particular Menu');
    return redirect()->back();
    }

In create.blade.php, I have taken few field to show the column name

        <form  id="1sform" action="" 
        method="post"  enctype="multipart/form-data" class="form- 
        bg1" >
        
        <div class="input-group control-group increment" >
        <div class="form-group">
        <label class="control-label"> Person Name</label>
        <input type="text" name="speker[]" class="form-control" 
        placeholder="" >
        <small class="form-control-feedback"> </small>
        </div>
        </div>

        <div class="clone hide">
        <div class="control-group input-group" style="margin-top:10px">
        <label class="control-label">Person Name</label>
        <input type="text" name="speker[]" class="form-control" placeholder="" >
        <small class="form-control-feedback"> </small>
        </div>
        </form>

        <form  id="2ndform" action="" method="post"  enctype="multipart/form-data" class="form-bg1" >
        

        <div class="input-group control-group increment" >
        <div class="form-group">
        <label class="control-label">Gamer Name</label>
        <input type="text" name="gamer[]" class="form-control" placeholder="" >
        <small class="form-control-feedback"> </small>
        </div>
        </div>

        <div class="clone hide">
        <div class="control-group input-group" style="margin-top:10px">
        <label class="control-label">Gamer Name</label>
        <input type="text" name="gamer[]" class="form-control" placeholder="" >
        <small class="form-control-feedback"> </small>
        </div>
        </form>



        <form  id="3rdform" action="" method="post"  enctype="multipart/form-data" class="form-bg1" >
        

        <div class="input-group control-group increment" >
        <div class="form-group">
        <label class="control-label">runner Name</label>
        <input type="text" name="runner[]" class="form-control" placeholder="" >
        <small class="form-control-feedback"> </small>
        </div>
        </div>

        <div class="clone hide">
        <div class="control-group input-group" style="margin-top:10px">
        <label class="control-label">runner Name</label>
        <input type="text" name="runner[]" class="form-control" placeholder="" >
        <small class="form-control-feedback"> </small>
        </div>
        </form>

and here is script

$('.form-bg1').submit(function () { alert($(this).attr("id")); return true; }) $("#clickMe").click(function () { $(".form-bg1").trigger('submit'); // should show 3 alerts (one for each form) });
<script type="text/javascript">

    $(document).ready(function() {

        $(".btn-outline-success").click(function(){
            var html = $(".clone").html();
            $(".increment").after(html);
        });

        $("body").on("click",".btn-danger",function(){
            $(this).parents(".control-group").remove();
        });

    });

</script>
<script type="text/javascript">

    $(document).ready(function() {

        $(".btn-skype").click(function(){
            var html = $(".clones").html();
            $(".incremental").after(html);
        });

        $("body").on("click",".btn-danger",function(){
            $(this).parents(".control-groups").remove();
        });

    });

</script>



via Chebli Mohamed

adding items with the same product id in the cart

i am trying to add a second product with the same id but different size, but i keeps overwriting the first product.

when i dd the condition it display that it is in fact true but even if it has a different size it just takes the place of the first product.

    if(isset($cart[$id])&&($cart[$id]['size']==$request->productSize)) {
        $cart[$id]['quantity'] += $request->productQuantity;

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');
    ;}


    if(isset($cart[$id])&&($cart[$id]['size']!==$request->productSize)) {
        $cart = [ 
            $id => [
                "name" => $product->productName,
                "price" => $product->productPrice,
                "size" => $request->productSize,
                "quantity" => $request->productQuantity,
                "photo" => $product->productImage
            ]
            ];

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Product added to cart successfully!');
    ;}

expected result is displaying 2 or more same product with same id but different sizes in the cart before checkout.



via Chebli Mohamed

Laravel Eloquent ORM Transactions: Why we need ROLLBACK?

Why we need DB::rollback() when we can execute multiple queries without using it. Such as follows:

DB::beginTransaction();
 //database queries here
DB::commit();

In the above case, even if any statement fails, commit will never hit, and the transaction won't process.



via Chebli Mohamed

Require MySQL Query for following situation [on hold]

I have a table like this:

<h3>id -- mem_id--amount--mode--dt</h3>
1 -- 1001-- 10-- A-- 2019-08-12<br />
2 -- 1001-- 30 -- C -- 2019-08-12<br />
3 -- 1001-- 20 -- C -- 2019-08-12<br />
4 -- 1001-- 30 -- B -- 2019-08-12<br />
5 -- 1001-- 20 -- D -- 2019-08-12<br />

I want to get a output like this:

<h3>Date -- Member -- A -- B -- C -- D</h3>
2019-08-12 -- 1001 --  10 -- 30 -- 50 -- 20

I want this query in Laravel Eloquent (or) MySQL RAW format.



via Chebli Mohamed

How to add laravel authentication to modal form instead of having a login page?

I am working on my first LARAVEL project and I have a pop up form that I want to use for user authentication . this is my form

laravel gives a custom form having its own page when i used php artisan:auth command , but I need to use mine



via Chebli Mohamed

Accept request with large amount of inputs (thousands)

Have an application that requires to submit a request with hundreds/thousands of inputs.

It seems like Laravel has a limit on the number of parameters on requests.

Here are some pictures of current request state:

  • enter image description here
  • enter image description here

Arrays don't go over 48 and last arrays don't go over 47.

How can I fix this?



via Chebli Mohamed

Add link in user drop down menu using Laravel

When a user is logged in they see the standard drop down menu in the top right (which is created by Laravel). I'd like to create a "Settings" page where logged in users can go to edit their personal info, upload profile photos etc.

I can't figure out how to add a link to the users drop down menu in the top right?

I've tried adding a link in web.php

Route::get('/settings', 'HomeController@settings')->name('settings');

I'm new to Laravel so am probably missing something obvious!



via Chebli Mohamed

How to get image as a resource instead of string in php using Storage::get()

I am trying to give user the photo with desired background that are stored in my server with the text they want on it. But to edit the image on the fly using php , i need to retrieve my background image file as resource but i am getting the image as string instead.

I tried using Storage::get() function

$bg_image = Storage::disk('public')->get('background.png');
imagettftext($bg_image, 64, 10, 20, 20, $color, $font, $user_name);

but it threw me an error imagettftext() expects parameter 1 to be resource, string given



via Chebli Mohamed

Already the multiple images are drawn in a single canvas but I can't display that canvas image in laravel project

I am trying to draw multiple images into a single canvas it is working in the separate file. When I am trying to add this tag in the e-commerce project which is on the basis of laravel framework the image is not displaying.

Already drawn the images into a single canvas. But failed to show the image in the laravel project.

           <canvas id="my-canvas" width="484" height="984"></canvas>

    <script>
       const getContext = () => document.getElementById('my-canvas').getContext('2d');


        const loadImage = url => {
          return new Promise((resolve, reject) => {
            const img = new Image();
            img.onload = () => resolve(img);
            img.onerror = () => reject(new Error(`load ${url} fail`));
            img.src = url;
          });
        };


        const depict = options => {
          const ctx = getContext();

          const myOptions = Object.assign({}, options);
          return loadImage(myOptions.uri).then(img => {
            ctx.drawImage(img, myOptions.x, myOptions.y, myOptions.sw, myOptions.sh);
          });
        };

        const imgs = [
          { uri: 'Group 8.png', x: 1, y:  15, sw: 484, sh: 984 },
          { uri: 'Rectangle 6.png', x: 46, y:  15, sw: 395, sh: 746 },
          { uri: 'Motif_2.png', x: 1, y: 15, sw: 484, sh: 984 },
          { uri: 'body_design_2.png', x: 46, y: 15, sw: 395, sh: 746 }
        ];

        imgs.forEach(depict);

    </script>

Want to display the canvas image in the e-commerce website which is made by using the laravel framework.



via Chebli Mohamed

mercredi 28 août 2019

My App stopped authenticating me all of sudden

I am working on Laravel 5.6 App. All of sudden it stopped authenticating me. I changed password by calling MD5 but it is not making change in the content of password because it can't authenticate even giving correct password.

What do I do?



via Chebli Mohamed

How to make Multiple sub query in Laravel

I am new in Laravel. Here below i mention my code how to make this in laravel query builder.

Using tables are ab,cd,ef,gh,ij

SELECT ab.* FROM ab WHERE ab.id IN (SELECT ab_id FROM cd WHERE ef_id = 1 AND status = 1 AND deleted_at IS NULL AND ab_id IN (SELECT ab_id FROM gh WHERE ij_id IN (SELECT id FROM ij WHERE ef_id = 1 AND deleted_at IS NULL) AND deleted_at IS NULL) AND ab_id IN (SELECT id FROM ab WHERE deleted_at IS NULL AND usertest != 1)) AND ab.deleted_at IS NULL GROUP BY ab.id ORDER BY ab.created_at DESC;



via Chebli Mohamed

How to get data from pivot table which has ids from three tables

I have three tables call Users, Services, Categories and pivot table call professionals. Also four models for all tables.

User: Id, name Services: id, service_name Categories: id, service_id, category_name Professionals: id, user_id, service_id, category_id

Relationships User has many Categories Service has many categories category can have one service category belongs to many users

$result = Professional::where('user_id’,’=‘,54)->get();

Above command give data like this, { "id": 1, "user_id": 54, "service_id": 8, "category_id": 20 }, { "id": 2, "user_id": 54, "service_id": 10, "category_id": 23 }, { "id": 3, "user_id": 54, "service_id": 9, "category_id": 21 }, { "id": 4, "user_id": 54, "service_id": 10, "category_id": 22 }

Please help me to get data from Professionals table with categories and services details related to a user, guide me how to make relations on models



via Chebli Mohamed

Laravel Unit Test - how to get meaningful output?

I am using Laravel 5.8 and I am trying to run tests using phpunit in my console but I keep getting
Expected status code 200 but received 409. Failed asserting that false is true.. I have validation errors set to return 409, however this error tells me nothing. How can I output or view more meaningful output like the full exception instead of this error message which doesn't help me at all. I have tried to disable the default error reporting but its not working $this->withoutExceptionHandling();

SaveResults Controller

public function save(Request $request) {

    $model = new User();

    $data = $request->all(); 
    $now = Carbon::now();
    $validator = Validator::make($data, $model->getValidationRules());
    // Here is where the error is thrown
    if($validator->fails()) {
        return response()->json(['error' => $validator->errors()->first()], 409);
}

Test.php

public function testCreateCachedData() {

    $this->withoutExceptionHandling();

    $this->withoutExceptionHandling();
    $user = factory(User::class)->create();
    $userRepo = factory(UserRepo::class)->create(['c_id' => $user->id]);


    $response = $this->post('/api/users/save', $$user->toArray());
    $response->assertStatus(200);
}



via Chebli Mohamed

app($classModel)->getQuery() != app($classModel)->query() or app($classModel)->getQuery() != $classModel::query()

Why is function getQuery() diferance to query() in model?

app($classModel)->getQuery() != app($classModel)->query() or app($classModel)->getQuery() != $classModel::query()



via Chebli Mohamed

Laravel Eloquent Query With Between And Just Month And Day

I have a date in the datatabase like this: 2019-08-28

I need to make a query where I can select the rows between two dates BUT just filtering the month and the day. I have this:

 $session_data = $request->session()->all();

 $date1 = date('Y-m-d');
 $date2 = date('Y-m-d', strtotime($date1. ' + 4 days'));

 $employees = Employee::whereBetween('born_date', array($date1, $date2))->take(4)->get();

but this selects does not work because it is filtering with the year..i need something which it uses this:

'DAY(born_date) = '. date('d')
'MONTH(born_date) = '. date('m'))

But I do not know how to add this with between.. Thanks



via Chebli Mohamed

Hour start and Hour end for an appointment

I am looking a way to create a form for an appointment, I have 2 fields so far, in format "string", is it correct according you?

<fieldset class="form-group ">
    <label for="company-content">Hour Start</label>
        <select name="hour_start" id="" class="form-control">
           <option value="">Hour Start</option>
           <option value="08:00" @if (old('hour_start') == "08:00") selected @endif>08:00</option>
           <option value="10:00" @if (old('hour_start') == "10:00") selected @endif>10:00</option>
        </select>
</fieldset>

 <fieldset class="form-group ">
    <label for="company-content">Hour End</label>
        <select name="hour_end" id="hour_end" class="form-control">
            <option value="">Hour End</option>
            <option value="10:00" @if (old('hour_end') == "10:00") selected @endif>10:00</option>
            <option value="13:00" @if (old('hour_end') == "13:00") selected @endif>13:00</option>
        </select>
</fieldset>

I think the validation will be complicated?

Thank you for your help.



via Chebli Mohamed

i keep getting "function name must be a string" error

I am building a site using laravel, and I got this error when trying to upload an image. I'm a beginner so, can I get some help?

$user = Auth::user();
    $user->name = $request('name');
    $user->update();
    $file = $request->file('image');
    $filename = $request->name . '-' . $user->id . '.jpg';



via Chebli Mohamed

Telegram for Laravel 5.8 [on hold]

I'm coding an app to send messages to different telegram channels where a telegramBot is administrator. I'm using https://github.com/babenkoivan/telegram-notifications but in the example, there is only one channel ID.

My idea is to get channel ID's from a table depending on a user role.

In babenkoivan code example:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable{
    use Notifiable;

    // ...
    public function routeNotificationForTelegram(){
        return '993344556';
    }
}

There is only one chat_id and don't know how return chat ID depending on one saved on a database table.



via Chebli Mohamed

Payment gateway open in new window, after payment completed redirect back to parent window with redirect URL

I want to open payment gateway page in new window page and after completing of payment redirect back to parent window with redirect URL.



via Chebli Mohamed

Laravel Eloquent Query Using WHERE with AND orWhere

I am beginner in Laravel. In use in my project Laravel 5.8. I have this array:

array:4 [
  0 => 1
  1 => 3
  2 => 4
  3 => 5
]

and function:

public function getPaymentMethods(array $paymentId)
    {
            dd($paymentId);
            return PaymentSettings::where('id', '=', $paymentId)->get();
    }

It's not working because in $paymentId I have array. How can I change my code function to use with array (many where/orWhere)?

I need something like this (but in laravel eloquent):

SELECT * from payment_settings where id = 1 or id = 3 or id = 4 or id = 5.



via Chebli Mohamed

Need some clarification on Cors

Good morning guys, I'm working on a vue project which makes a get request to an api on a different website using axios. Well, I encountered an error which reads, "No Access-control-allow-origin header" , so I did some research and I understand the browser is only blocking the request due to the Same origin policy implementation (which I understand now). So I got a quick fix which was to add a chrome extension which I think is cool for dev purposes, but my concern is when it gets to production, How I'm I going to fix this so that my clients wouldn't have to install this chrome extension.? Would i have to route the request through a proxy? If so kindly suggest some useful resources to help me out. And If my understanding of cors Is wrong, kindly help with some clarification, thanks. Using vue n laravel



via Chebli Mohamed

Add days to date in Laravel

I am beginner in Laravel. I use in my project Laravel 5.8.

I have this code:

$userPromotionDays = $user->premiumDate; // 2019.08.28
$daysToAdd = 5

How can I add $userPromotionDays to $daysToAdd (in Laravel/Carbon)?



via Chebli Mohamed

parse error syntax error unexpected ' ' expecting variable (t_variable) in my laravel 5.5

"I am using laravel 5.5 version and my php version is 7.0 when my project setup on ubuntu server and open my project on browser showing these error Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_PARSE) Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE)"

Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_PARSE) Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE)



via Chebli Mohamed

Allow only authenticated users to access API routes

I want to allow only authenticated users to access some API routes. I use the default Laravel authentication system. After the default login, I want to be able to access a route, but I get the "Unauthenticated" message.

So, after login, I am redirect to the home route which uses the HomeComponent file. Here, using axios, I am making a call to the step API route where I am trying to get the id of the authenticated user, but instead I receive an error message. What am I doing wrong?

api.php

Route::middleware('auth:api')->group(function () {
    Route::get('application/step', ['as' => 'application.step', 'uses' => 'ApplicationController@step']);
});

ApplicationController.php

public function step() {
    print_r(auth()->user());
    die('---');

    // code to get authenticated user step
    return json_encode(array('step' => 7));
}

LoginController.php

public function login(Request $request)
{
    $this->validate($request, [
        'email'   => 'required|email',
        'password' => 'required|min:6'
    ]);

    $user = User::where('email', $request->email)->firstOrFail();
    if ($user && !$user->isAdmin()) {
        if (Auth::attempt(['email' => $request->email, 'password' => $request->password], true)) {
            $token = $user->createToken('TokenName')->token;
            $token->save();

            return redirect()->route('home');
        }
        else {
            return back()->withInput($request->only('email'));
        }
    }

    return back()->withInput($request->only('email'))->withErrors(['denied' => 'You are not allowed to access this page.']);
}

HomeComponent.vue

...
getStep() {
    axios.get("/api/application/step")
         .then((response) => {
             this.step = response.data.step;
         })
         .catch((err) => {
             console.log('Cannot get step', err);
         });
} 



via Chebli Mohamed

Authorise a user with Laravel Passport when testing RESTful controllers update method

Every time I run the test, I'm getting a 403 response status, what am I doing wrong in here? I have tried to remove Passport authorization from the test, but then I'm getting a redirect to a login page, 302 status response.

//PostTest:

public function test_can_update_post()
{
    //creating a user
    $user = factory(User::class)->create();

    //creating an author for post
    $author = factory(Author::class)->create([
        'user_id' => $user->id,
    ]);

    //creating a post
    $post = factory(Post::class)->create([
        'author_id' => $author->id,
    ]);

    $data = [
        'title' => $this->faker->title,
        'content' => $this->faker->paragraph,
    ];

    //authorizing user
    //I have tried to remove this line, then I'm gettig a redirect to login page 302
    $user = Passport::actingAs($user, ['posts/' . $post->id]);

    $this->actingAs($user)
        ->patch(route('posts.update', $post->id), $data)
        ->assertStatus(200);// why I'm getting 403???
}

//API route:

Route::patch('posts/{post}')
    ->uses('PostController@update')
    ->middleware('auth:api')
    ->name('posts.update');


//PostController update method:

public function update(PostUpdateRequest $request, Post $post)
{
    $this->authorize('update', $post);

    $post->title = $request->input('title');
    $post->content = $request->input('content');

    $post->save();

    return new PostResource($post);
}

//PostPolocy

public function update(User $user, Post $post)
{
    return Author::where('user_id', $user->id)->first()->id === $post->author_id;
}

I expect response status 200



via Chebli Mohamed

get correct record form many to many relation accoring to locale lang

i have 3 table Hotel, Hotel_feature, Hotel_Hotel_feature

hotel and hotel_feature have many to many relation and Hotel_Hotel_feature is pivot table. also i have another table named languages that i save language name and slug.

tables structure:

HOTEL: 
    id,
   name,
  ..

HOTEL_FEATURE:
  id
  language_id
  name
  slug

 HOTEL_HOTEL_FEATUE
   hotel_id
   hotel_feature_id

 LANGUAGE 
   id
   name
   slug

i wrote a accessor in Hotel model to get current hotel features according to current locale lang

public function getFeatureTranslateAttribute()
{
    $lang = app()->getLocale();

    // get correct features for current hotel model
    $features = $this->hotelFeatures()->whereHas('language', function($q) use ($lang){
        $q->where('name', 'en');
    })->where('hotel_id', $this->id)->first();


    dd($features);

    return $features ?: $this;

}

but it returning null ... how can i get correct hotel features for current hotel according to locale?



via Chebli Mohamed