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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2MQVnsP
via IFTTT

How to check if translatable are null

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


      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();
            });
     ```

    ``` 
          $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();




from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/30KyLh4
via IFTTT

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'
         }
    ]
  }
]



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LkzAXr
via IFTTT

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.


@extends('layouts.master')

@section('title')
    Laravel product page
@endsection

@section('content')
@foreach($products->chunk(3) as $productChunk)



    <div class="row">
    @foreach($productChunk as $product)
    <div class="col-sm-6 col-md-4">
            <div class="thumbnail">
                <img src="" alt="..." class="img-responsive">
                <div class="caption">
                    <h3></h3>
                    <p class="description">""</p>
                    <div class="clearfix">
                        <div class="pull-left price">£</div>
                           <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

                    </div>
                </div>
            </div>
        </div>
    @endforeach


    </div>
   @endforeach
@endsection







from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32i89UV
via IFTTT

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();

    }



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2PwHXog
via IFTTT

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');
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZIW4q8
via IFTTT

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()



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZGAdQr
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Ld3MF5
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZHw8eF
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/30R6aGY
via IFTTT

How to display raw JSON in laravel?

I have 3 tables projects, users, project_time_logs. I'm trying to join them and then generate a table, however when I pull the results nothing displays. I believe is a JSON error either in my controller or route because when I pull the JSON url no data is displayed. Any thoughts are greatly appreciated.

Route

Route::get('time-log-report/data/{startDate?}/{endDate?}/{projectId?}/{employee?}', ['uses' => 'TimeLogReportController@data'])->name('time-log-report.data');

Controller

public function data($startDate = null, $endDate = null, $employeeId = null, $projectId = null) {

$timeLogs =\App\ProjectTimeLog::leftJoin('projects', 'projects.id', '=', 'project_time_logs.project_id')
->join('users', 'users.id' ,'=' ,'project_time_logs.user_id')
->select('users.name','projects.project_name','project_time_logs.start_time','project_time_logs.end_time' ,'users.name'); 

if(!is_null($startDate)){
    $timeLogs->where(DB::raw('DATE(project_time_logs.`start_time`)'), '>=', $startDate);
}

if(!is_null($endDate)){
    $timeLogs->where(DB::raw('DATE(project_time_logs.`end_time`)'), '<=', $endDate);
}

if($projectId != 0){
    $timeLogs->where('project_time_logs.project_id', '=', $projectId);
}

if($employeeId != 0){
    $timeLogs->where('project_time_logs.user_id', $employeeId);
}
$timeLogs->get();

    return DataTables::of($timeLogs)

                ->editColumn('start_time', function($row){
                    return $row->start_time->timezone($this->global->timezone)->format($this->global->date_format.' '. $this->global->time_format);
                })
                ->editColumn('end_time', function($row){
                    if(!is_null($row->end_time)){
                        return $row->end_time->timezone($this->global->timezone)->format($this->global->date_format.' '.$this->global->time_format);
                    }
                    else{
                        return "<label class='label label-success'>".__('app.active')."</label>";
                    }
                })
                ->editColumn('name', function($row){
                    return ucwords($row->user->name);
                })
                ->editColumn('project_name', function($row){
                    return ucwords($row->project->project_name);
                })
                ->editColumn('total_hours', function($row){
                    $timeLogs = intdiv($row->total_minutes, 60).' hrs ';

                    if(($row->total_minutes % 60) > 0){
                        $timeLogs= ($row->total_minutes % 60).' mins';
                    }

                    return $timeLogs;
                })

                ->rawColumns(['end_time', 'start_time', 'name','project_name'])
                ->make(true);
        }



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2PuTvbH
via IFTTT

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');
    }




from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/30Qaeak
via IFTTT

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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZE0W46
via IFTTT

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)



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZBfIV6
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LcAbdy
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZoAdcm
via IFTTT

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'
  }
]



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HzWOYE
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/348x9jr
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zwlCfA
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HDhZsS
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32iHlEd
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LlGkEF
via IFTTT

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.


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2UiLncR
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zv2ONF
via IFTTT

How to select specific HybridRelations in laravel?

Hi i have on 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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZF0cYq
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZypGqk
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Psy1Mk
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/30KO8WF
via IFTTT

Create Laravel Package but Command not Listed On Artisan

I've been create simple package here is the structure of my directory and using laravel 5.4

├── 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 ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/34ceX8E
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2UgF35H
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LaNTO4
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZsNeli
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Ld44KY
via IFTTT

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"



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zvQb55
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LfVCL6
via IFTTT

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"?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Zxk1ER
via IFTTT

I wrote a csrf tag, but somehow 419 came back

I am writing @csrf but getting 419 error

WorkController.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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zv60sN
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zvk6KH
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HyUSPT
via IFTTT

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');
}


}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32c8SqP
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2UcQuvg
via IFTTT

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".



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32ed1ug
via IFTTT

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');;
    }



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zwNWOS
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zx4Eh2
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32gJWyf
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2L1Haay
via IFTTT

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);



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZlFsJP
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2HyjJmY
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2MKk5uV
via IFTTT

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>



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zsHkku
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2PivJiT
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32blZbO
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2zpAgp1
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/30KQKUw
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2Zo5eNt
via IFTTT

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!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ZCcgxq
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/340Ibae
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2UacYgq
via IFTTT

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?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2L0yAZz
via IFTTT

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;



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2LgVGKh
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2MIKJ7y
via IFTTT

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);
}



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32bZ6F2
via IFTTT

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()



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2PjuuQw
via IFTTT

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



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2NDFbeo
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/346WxG2
via IFTTT

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';



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/30EaUQg
via IFTTT

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.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2L0JDBV
via IFTTT