lundi 30 avril 2018

Laravel Eloquent: Multiple Wheres with OrWhere

I have a search feature inside my app that will search a "broad" search term of several columns or a defined column as the user selects. I also have an outside where statement that is searching for the the company id (multi tenant app) and the assigned subcompany_id, both belonging to the user.

When I search, I'm getting all results and it's not using the company_id or subcompany_id relating to the user. I figured out that it's using the subcompany_id within the or where statement brackets rather it being outside the bracket.

Version: Laravel 5.6

$request->broad = Checkbox for broad search.

Query:

$Leads = Lead::with('Bank')
                ->with('BankBranch')
                ->with('Account')
                ->with('LeadStatus')
                ->with('SalesRep')
                ->when($HideAccounts == True, function ($HideAccounts) {
                    $HideAccounts->where('lead_merchant_id', '');
                })
                ->when(isset($request), function ($CustomSearch) use ($request) {
                    $CustomSearch->when(!empty($request->broad), function ($BroadSearch) use ($request) {
                        $BroadSearch->where('lead_name', 'LIKE', '%' . $request->broad . '%')
                            ->orWhere('lead_contact', 'LIKE', '%' . $request->broad . '%')
                            ->orWhere('lead_phone1', 'LIKE', '%' . $request->broad . '%')
                            ->orWhere('lead_phone2', 'LIKE', '%' . $request->broad . '%')
                            ->orWhere('lead_merchant_id', $request->broad)
                            ->orWhere('secondary_mid', $request->broad)
                            ->orWhere('lead_address_city', $request->broad)
                            ->orWhere('lead_address_state', $request->broad)
                            ->orWhere('lead_address_zip', 'LIKE', '%' . $request->broad . '%');
                    });

                    if(!empty($request->company_name)) {
                        $CustomSearch->where('lead_name', 'LIKE', '%' . $request->company_name . '%');
                    }

                    if(!empty($request->lead_contact)) {
                        $CustomSearch->where('lead_contact', 'LIKE', '%' . $request->lead_contact . '%');
                    }

                    if(!empty($request->address_city)) {
                        $CustomSearch->where('lead_address_city', $request->address_city);
                    }

                    if(!empty($request->address_state)) {
                        $CustomSearch->where('lead_address_state', $request->address_state);
                    }

                    if (!empty($request->sic_code)) {
                        $CustomSearch->where('lead_sic_code', 'LIKE', '%' . $request->sic_code . '%');
                    }

                    if (!empty($request->lead_leadstatus_id)) {
                        $CustomSearch->where('lead_leadstatus_id', $request->lead_leadstatus_id);
                    }

                    if(!empty($request->address_zip)) {
                        $CustomSearch->where('lead_address_zip', 'LIKE', '%' . $request->address_zip . '%');
                    }

                    if(!empty($request->phone)) {
                        $CustomSearch->where('lead_phone1', $request->phone);
                        $CustomSearch->orWhere('lead_phone2', $request->phone);
                    }

                    if (!empty($request->lead_referral_user_id)) {
                        $CustomSearch->where('lead_referral_user_id', $request->lead_referral_user_id);
                    }

                    if (!empty($request->lead_sales_representative_id)) {
                        $CustomSearch->where('lead_sales_representative_id', $request->lead_sales_representative_id);
                    }

                    if (!empty($request->lead_referral_bank_id)) {
                        $CustomSearch->where('lead_referral_bank_id', $request->lead_referral_bank_id);
                    }

                    if (!empty($request->lead_referral_bankbranch_id)) {
                        $CustomSearch->where('lead_referral_bankbranch_id', $request->lead_referral_bankbranch_id);
                    }

                    if (!empty($request->lead_created)) {
                        $LeadCreated = Carbon::createFromFormat('M d, Y', $request->lead_created)->startOfDay();

                        if (!empty($LeadCreated)) {
                            $CustomSearch->where('lead_created_timestamp', '>=', $LeadCreated);
                        }
                    }

                    if (!empty($request->lead_created_end)) {
                        try {
                            $LeadCreatedEnd = Carbon::createFromFormat('M d, Y', $request->lead_created_end)->startOfDay();
                        } catch (\Exception $e) {
                            $LeadCreatedEnd = NULL;
                        }

                        if (!empty($LeadCreatedEnd)) {
                            $CustomSearch->where('lead_created_timestamp', '<=', $LeadCreatedEnd);
                        }
                    }

                    if (!empty($request->account_approval_start)) {
                        try {
                            $AccountApprovalStart = Carbon::createFromFormat('M d, Y', $request->account_approval_start)->startOfDay();
                        } catch (\Exception $e) {
                            $AccountApprovalStart = NULL;
                        }

                        if (!empty($AccountApprovalStart)) {
                            $CustomSearch->whereHas('Account', function ($Account) use ($AccountApprovalStart) {
                                $Account->where('account_created_timestamp', '>=', $AccountApprovalStart);
                            });
                        }
                    }

                    if (!empty($request->account_approval_end)) {
                        try {
                            $AccountApprovalEnd = Carbon::createFromFormat('M d, Y', $request->account_approval_end)->startOfDay();
                        } catch (\Exception $e) {
                            $AccountApprovalEnd = NULL;
                        }

                        if (!empty($AccountApprovalEnd)) {
                            $CustomSearch->whereHas('Account', function ($Account) use ($AccountApprovalEnd) {
                                $Account->where('account_created_timestamp', '<=', $AccountApprovalEnd);
                            });
                        }
                    }
                })
                ->where('lead_company_id', Auth::user()->user_company_id)
                ->when(Auth::user()->user_subcompany_id != NULL, function ($query) {
                    return $query->where('lead_subcompany_id', Auth::user()->user_subcompany_id);
                });

This code returns the following query:

select count(*) as aggregate from `leads` where (`lead_name` LIKE '%tire%' or `lead_contact` LIKE '%tire%' or `lead_phone1` LIKE '%tire%' or `lead_phone2` LIKE '%tire%' or `lead_merchant_id` = 'tire' or `secondary_mid` = 'tire' or `lead_address_city` = 'tire' or `lead_address_state` = 'tire' or `lead_address_zip` LIKE '%tire%' and `lead_deleted` = '0' and `lead_duplicate` <> '1' and `lead_company_id` = '1' and `lead_subcompany_id` = '1') and `leads`.`lead_deleted_timestamp` is null

What it should be doing:

select count(*) as aggregate from `leads` where (`lead_name` LIKE '%tire%' or `lead_contact` LIKE '%tire%' or `lead_phone1` LIKE '%tire%' or `lead_phone2` LIKE '%tire%' or `lead_merchant_id` = 'tire' or `secondary_mid` = 'tire' or `lead_address_city` = 'tire' or `lead_address_state` = 'tire' or `lead_address_zip` LIKE '%tire%' and `lead_deleted` = '0' and `lead_duplicate` <> '1') and `lead_company_id` = '1' and `lead_subcompany_id` = '1' and `leads`.`lead_deleted_timestamp` is null`

How can I achieve this using Laravel Eloquent?



via Chebli Mohamed

Laravel Mongodb Error

I just started converting mysql to nosql (Mongodb) and after convertion it's showing some error like this:

Trying to get property 'size' of non-object 

This is the code below i used

class PanelController extends Controller
{

    public function index()
    {
       $userid = Auth::user()->id;
       $users = DB::collection('Booking')->where('Uid', '>=', $userid)->get();
      return view('panel.main')->with('records',$users);
    }
}

In the view i'm using like this,

@foreach ($records as $rec)

@endforeach

So please someone can help me with this would be much appreciated.



via Chebli Mohamed

Laravel routing different in two ambients

I have 2 ambients, one for Local development (in Ubuntu for Windows 10), where I run my server withphp artisan serve --port=123 and I access through http://127.0.0.1:123/ and another one in a shared host called Dev, where I access to through this URL: http://dev.example.com/my_project/public/

In my routes I have this:

Route::redirect('/', '/inicio', 301);
Route::get('inicio', 'DashboardController@index')->name('inicio');

In Local, when I access to http://127.0.0.1:123/ it redirects to http://127.0.0.1:123/inicio which is correct. But in Dev if I join to http://dev.example.com/my_project/public/ it redirects to http://desa.laravel.com/inicio Why is happening that?. Plus, in Local and in Dev, if I use: href=""> both sites sends me to where I need, which is http://127.0.0.1:123/inicio and http://dev.example.com/my_project/public/inicio respectively.



via Chebli Mohamed

Laravel Storage put returns true by the files not completely uploaded

I'm using Laravel Storage with S3 to add files to a bucket. When running Storage::disk('s3')->put('myfile.zip', 'myfile.zip') in artisan it returns true. However, the file locally is 15mb but then on S3 it's 18b. No error in the php log. Don't know where to look next.



via Chebli Mohamed

Laravel + vue js and vue2-google-maps

So i'm having some trouble with this library , i think i set up everything correctly but my component is not rendering , i get just a blank page with no errors in the console . This is my code :

Map Component

  <template>
      <div >
        <gmap-map :center="{lat:1.38, lng:103.8}" :zoom="12">
          <gmap-marker :position="{lat:1.38, lng:103.8}">
          </gmap-marker>
          <gmap-info-window :position="{lat:1.38, lng:103.8}">
            Hello world!
          </gmap-info-window>
        </gmap-map>
      </div>
    </template></strike>



    <script>
      export default {

      }
    </script>

    <style>
      .map-container, .vue-map-container {
        display: flex;
        width: 100%;
      }
    </style>'

Main.js

require('./bootstrap');
import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import VueRouter from 'vue-router';
import routes from './routes';

import * as  VueGoogleMaps from 'vue2-google-maps'

Vue.use(VueGoogleMaps, {
  load: {
    key: 'My_api_key',
    v: '3.31',
    libraries: 'places'
  }
})


Vue.use(VueRouter);
const router = new VueRouter({
    routes
});


window.Vue = require('vue');


Vue.component('navbar-component', require('./components/LayoutComponents/NavbarComponent.vue'));
Vue.component('home-component', require('./components/HomeComponent.vue'));
Vue.component('map-component', require('./components/MapComponent.vue'));
Vue.component('footer-component', require('./components/LayoutComponents/FooterComponent.vue'));
Vue.component('register-component', require('./components/AuthComponents/RegisterComponent.vue'));
Vue.component('login-component', require('./components/AuthComponents/LoginComponent.vue'));



const app = new Vue({
    el: '#app',
    router
});

The router handles everything correctly but for some reason it won't load the map component when i have the map related code in it , if i put some text there it will load everything correctly . I installed vue2-google-maps with npm , it shows up in the package.json file correctly . I'm very new to Vue in general so I did my best to be on point .



via Chebli Mohamed

Class path is not found in laravel

I wrote this code to seperate the class definition of "attractions" so that I could reuse it elsewhere. I will need it from multiple pages.

So the deal is that it is unable to find the part no matter what i do.

This is the definition of the class and you can also see the folder structure. This is the definition of the class and you can also see the folder structure.

trying to create an object $task of the type class trying to create an object $task of the type class

This is the error that pops up "Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Class 'App\MyClasses\attractions\attractions' not found"

The screenshot of the error that pops up enter image description here

I tried every possible thing with the path but this would not be acceptable..

Any help? (I know this might be a very stupid and trivial mistake!)



via Chebli Mohamed

Laravel, need variable on admin routes

I need a variable for my admin dashboard, so my guess is to put something inside cache so I can do I can access it in my admin layout-template.

if (!\Cache::has('admin-menu')) {
 \Cache::set('admin-menu', ['some' => 'data']);
}

Should I put it inside route middleware or somewhere else like the RouteServiceProvider? I am not that good in programming so I don't know what is the best approach.



via Chebli Mohamed

Eloquent order relationship results

I have a simple eloquent query and want to include another table with my results, however, the order of relationship results is incorrect.

Is it possible to order the results without using an SQLRAW statement

$groups = AttributeGroup::with('attribute')->where('page_id', $page->id)->get();

What I would like -

$groups = AttributeGroup::with('attribute')->orderBy('iteration', 'DESC')->where('page_id', $page->id)->get();



via Chebli Mohamed

Which is the best folder to store the images/files in Laravel?

Which is the best folder to store the images/files on server in Laravel ? Public or Storage?



via Chebli Mohamed

How to use where and skip in same condition for Laravel queries ?

I have a news website and in a partial i must skip first 5 headline articles and fetch others.

There are 2 parts on my page. One is slider ( for headline posts ) and second is for other posts ( non-headline articles and headline articles after last 5 )

My query is not working. I think i need two conditions on my where query. skip where is headline and last 5 posts..

This query does not work :

 ->where('headline', '=', '1')->skip(5)

How can i achieve this ?



via Chebli Mohamed

Laravel relationship query where using array

I'm trying to return all the attributes from my database that have a set foreign key (Attribute groups). I've set up all the relationships in my model but I'm unsure how to query these relationships using a collection or array.

AttributeGroup -

public function attribute()
{
    return $this->hasMany('App\Attribute', 'group_id');
}

Attribute -

public function attributeGroup()
{
    return $this->belongsTo('App\AttributeGroup');
}

My current query -

$page = Page::where('slug', $slug)->firstOrFail();

$groups = AttributeGroup::where('page_id', $page->id)->get()->toArray();

$atts = Attribute::where('group_id', $groups[0]['id'])->get();

This works because we have set the specific index of the array using $groups[0]

Is there a simple way I can pass an array through to the query using their relationships or is the method below the best way?

$attributes = array();
foreach ($groups as $group){
   array_push($attributes, $group['id']);
}
$atts = Attribute::where('group_id', $attributes)->get();



via Chebli Mohamed

Authorization for laravel passport through socket.io for broadcasting channels

I'm using laravel 5.3 + passport for authorization, Laravel is my back-end API which is restfull.

front-end is written in angular-js which communicate with API with rest requests.

For Real-time notifications I've used laravel broadcasting events + redis, and socket.io for socket server and socket client in angular-js.

I want to authorize these events and I've done it far as I could :

BroadcastServiceProvider :

 public function boot()
    {
        Broadcast::routes(['middleware' => ['api']]);

        /*
         * Authenticate the user's personal channel...
         */
        Broadcast::channel('App.User.*', function ($user, $userId) {
            return (int) $user->id === (int) $userId;
        });

        Broadcast::channel('notifs.*', function ($user, $userId) {
            return $user->id === (int) $userId;
        });
    }

This is my socket.js code which runs my socket server :

var app   = require('express')();
var http  = require('http').Server(app);
var io    = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();

redis.psubscribe('*', function(err, count) {});

redis.on('pmessage', function(subscribed, channel, message) {
    console.log(channel);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

http.listen(3000, function () {
    console.log('Listening on Port 3000');
});

redis.on("error", function (err) {
    console.log(err);
});

The problem is I don't know how to authenticate this broadcasting events in socket server and also how to authorize user in angular-js (SPA) to listen to these events.

I'd appreciate any help.



via Chebli Mohamed

Type error: Too few arguments to function createRoute(), 0 passed and exactly 3 expected in RoutesController

I'm working on Laravel 5.6,

I'm creating a function that receives three parameters ($name_route, $description_route, $photo_route) that I would like to be inserted on table Route, but I'm having the following error that can't explain:

"Type error: Too few arguments to function App\Http\Controllers\RoutesController::createRoute(), 0 passed and exactly 3 expected in RoutesController.php (64)"

What am I doing wrong if I'm passing those three variables? I'm testing using Swagger. Can you help to guess what's going wrong? Never happened to me something like this.

Thanks in advance!!

Here's how I'm setting in my routes file (routes.php):

 /** ***********************************************************
 *  Logged user can create a route
 * ************************************************************
 * @SWG\Post(
 *      tags={"Routes"},
 *      path="/api/v1/routes/route/create",
 *      summary="Logged user can create a route",
 *      @SWG\Parameter(ref="#/parameters/Accept"),
 *      @SWG\Parameter(ref="#/parameters/apikey"),
 *      @SWG\Parameter(ref="#/parameters/Language"),
 *      @SWG\Parameter(ref="#/parameters/Authorization"),
 *      @SWG\Parameter(name="name", in="path", type="string"),
 *      @SWG\Parameter(name="description", in="path", type="string"),
 *      @SWG\Parameter(name="photo", in="path", type="string"),
 *      @SWG\Response(response=HTTP_CODE_200_OK, description="Routes", 
        @SWG\Schema(ref="#/definitions/RouteDetail")),
 * )
 */
Route::post('/route/create', 'RoutesController@createRoute')->middleware('auth:api');

And my controller:

 /**
 * @param $name_route
 * @param $description_route
 * @param $photo_route
 */
public function createRoute($name_route, $description_route, $photo_route)
{
    $route = new Route();

    $route->user_id = $this->input($this->user()->id);
    $route->name = $this->input($name_route);
    $route->description = $this->input($description_route);
    $route->photo = $this->input($photo_route);

    $route->save();
}



via Chebli Mohamed

Laravel Eloquent compare dates by specific format

I am having a little trouble comparing dates in Laravel, where the date is a specific format. The field in the database has the date like this d-m-Y(20-04-2018) and I am trying to get a result where this date is greater than the date now using this.

$check= Usersubstitutions::where([
   ['user_id', '=', $request->user],
   ['date_to', '>=', date("d-m-Y")]
])->first();

And it never works. I var dumped to see what compares, using a foreach and it says that 20-05-2018 is NOT greater than 04-04-2018.



via Chebli Mohamed

Why do we use Command lines Artisan to create controllers & Models in Laravel

It might be a silly question but I have to ask, why do we need use command lines for everything in laravel ?!! to create a controller, we need to type the following command line

Php artisan make:controller FileController 

or for migrate DB

php artisan migrate

and why DB even should be created within laravel code.

and can we do all those things just by doing a regular way in PHP, which creates a page of controller and types the things on?

I find that confusing little bit and a little bit out of control on and relay alot on command line, than understand the relationship between pages and linking things, like why got model and controller, does create with command line means there is another dependence on those pages and code be amendment in another area in laravel that I dind't know.



via Chebli Mohamed

Laravel - npm install - npm WARN deprecated gulp-util@3.0.8: gulp-util is deprecated

I want to start a project by Laravel and Reactjs. For the first I installed a fresh Laravel project, and then run this commend in the project library

npm install

but I got this message and no any more progress.

 npm WARN deprecated gulp-util@3.0.8: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5

how i can fix this?



via Chebli Mohamed

dimanche 29 avril 2018

Laravel Sum Eloquent sum of multiple multiplications from two different tables

Currently, in my Laravel project controller, I am using one query

public function cartreview(Request $request,$sp_id, $service_id,$cart_id)
    {
    $total = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.shirt*carts.quantity_shirt ) AS total'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();
    }

In above query, I am using two database tables as pricings and carts where I am calculating total bill price of shirt item by getting a price from pricing table and quantity from carts table.

Now I also want to add another item with a shirt like a pant, tie, etc. How do I pass more multiplication to the sum?

Please help me with the syntax. Can I do something like this

    $total = DB::table('pricings')
        ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
        ->select(DB::raw('sum(pricings.shirt*carts.quantity_shirt ,
                             pricings.pant*carts.quantity_pant , 
                             pricings.tie*carts.quantity_tie) AS total'))                      
        ->where('pricings.sp_id', '=', $sp_id)
        ->where('carts.id', '=' , $cart_id)
        ->first();

OR even if I calculate total separately for each item How do I add it?

$total_shirt = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.shirt*carts.quantity_shirt ) AS total_shirt'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();

   $total_pant = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.pant*carts.quantity_pant ) AS total_pant'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();

   $total_tie = DB::table('pricings')
    ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
    ->select(DB::raw('sum(pricings.tie*carts.quantity_tie ) AS total_tie'))                      
    ->where('pricings.sp_id', '=', $sp_id)
    ->where('carts.id', '=' , $cart_id)
    ->first();

$total = $total_shirt + $total_pant + $total_tie; ?

To display value in view.blade.php I use something like

Thanks in advance.



via Chebli Mohamed

Error : htmlspecialchars() expects parameter 1 to be string, object given

Error : ErrorException (E_ERROR) htmlspecialchars() expects parameter 1 to be string, object given

Help me understand and get rid of such errors. Currently in my controller :

public function cartreview(Request $request,$sp_id, $service_id,$cart_id)
     {
     total = DB::table('pricings')
     ->join('carts', 'carts.sp_id', '=', 'pricings.sp_id')
     ->select(DB::raw('sum(pricings.Shirt*carts.q_Shirt) AS total_price'))
     ->where('pricings.sp_id', '=', $sp_id)
     ->where('carts.id', '=' , $cart_id)
     ->first();

    return view('user.cartreview')->with('total', $total );
}

In view:



via Chebli Mohamed

PhpSpreadsheet chunk filter read returning empty rows

I'm trying to read an XLSX file by chunks. But some of the chunks are empty on the var_dump out put. I'm using PHP7.2 and Laravel 5.5 framework.

That is what I've tried so far:

Filter

class ChunkReadFilter implements IReadFilter
{
private $startRow = 0;
private $endRow   = 0;

// Set the list of rows that we want to read  
public function setRows($startRow, $chunkSize) {
    $this->startRow = $startRow;
    $this->endRow   = $startRow + $chunkSize;
}

public function readCell($column, $row, $worksheetName = '') {
    //  Only read the heading row, and the configured rows
  // if (($row == 1) || ($row >= $this->startRow && $row < $this->endRow)) {
 if (($row >= $this->startRow && $row < $this->endRow)) {
        if (in_array($column, range('A', 'L'))) {
            return true;
        }

    }
    return false;
}
}

Code

$inputFileType = 'Xlsx';
$inputFileName = $path;

$reader = IOFactory::createReader($inputFileType);
$chunkSize = 100;
$chunkFilter = new ChunkReadFilter();
for ($startRow = 1; $startRow <= 800; $startRow += $chunkSize) {

     //Tell the Read Filter which rows we want this iteration  
    $chunkFilter->setRows($startRow,$chunkSize);
    //Tell the Reader that we want to use the Read Filter 
    $reader->setReadFilter($chunkFilter);
    //Load only the rows that match our filter  
    $spreadsheet = $reader->load($inputFileName);
    //Do some processing here
    $sheetData = $spreadsheet->getActiveSheet()
   ->toArray(null, true, true, true);

      var_dump($sheetData);
   }



via Chebli Mohamed

Sidebar with dropdown menu from database

Im trying to use a database to add menu items on a sidebar on my site. My database structure is the following:

ID / Product_Name/ Product_Type
1 / product1 / type1
2 / product2 / type1
3 / product3 / type2
4 / product4 / type2

I need a sidebar which has each type listed as a menu item, with the products belonging to that type as the submenu items:

  Type1
    product1 
    product2 
  Type2
    product3
    product4

With my current code however I achieve each menu item but my submenu shows every product in the entire database instead of just the products belonging to that type.

My controller:

     public function index()
{

    //get all products
    $products = Product::all();  

    //get each type
    $types = Product::distinct()->get(['Type']);


    return view('pages.getstarted')->with('products', $products)                                       
                                   ->with('types', $types);

}

My view:

    <ul class="list-sidebar">                                

          @foreach($types as $type)

        <li class="header"> <a href="#" data-toggle="collapse" data-target="#1"><span class="fa fa-chevron-left pull-right"></span> </a>
                <ul class="sub-menu collapse" id="1">
                @foreach($products as $product) <li><a href="1"></a></li> @endforeach
                </ul>
              </li>   

          @endforeach 

        </ul>    

I am very new to Laravel so any help would be appreciated.



via Chebli Mohamed

The view is loading loading a different route when i reload several times

I have a view that has a route but when i reload that view/page it picks a different route from one of the routes, i have tried to figure it out but no answers so far. can someone help out please? Thank you.



via Chebli Mohamed

Sort a resource collection in Fractal by an included primitive

I'm using the PHP Fractal library for my Laravel API responses. My model is a Post that has many Comments. What I want to do is to get all posts sorted by the amount of comments it has received in the last X days. Basically this API call:

GET /api/posts?include=comment_count:since_days(7)&sort=comment_count:desc`

Therefor I'm using a PostTransformer that parses the include parameter and adds a primitive resource if this include is requested:

class PostTransformer extends TransformerAbstract 
{

  // ...

  public function includeCommentCount(Post $post, ParamBag $params = null) 
  {
    $sinceDays = // ... extract from ParamBag

    $commentCount = $post->getCommentCountAttribute($sinceDays);

    return $this->primitive($commentCount);
  }
}

The include is working fine and allows to specify the since_days parameters as it is intended in the Fractal library. However, I'm not sure on how to sort the posts now. This is my PostController:

class PostController extends Controller
{
  // ...

  public function index(Request $request)
  {
    $orderCol, $orderBy = // ... parse the sort parameter of the request

    // can't sort by comment_count here, as it is added later by the transformer
    $paginator = Post::orderBy($orderCol, $orderBy)->paginate(20);
    $posts = $paginator->getCollection();

    // can't sort by comment_count here either, as Fractal doesn't allow sorting resources
    return fractal()
      ->collection($posts, new PostTransformer())
      ->parseIncludes(['comment_count'])
      ->paginateWith(new IlluminatePaginatorAdapter($paginator))
      ->toArray();
  }
}

Is there a solution to this problem?



via Chebli Mohamed

Laravel - Error: 500. Update record with Ajax

In Laravel 5.5,

I want to update a row using ajax in vanilla js. I have an error, 500 (internal server error). Is it due to the CSRF token? If so, how do I add it to send for the update?

Below are the codes;

// I have an object that stores:
params = {
    method: "PUT", 
    _token: "uq1Ipn0ehw9Ias5vsgy1pT3ckq4OhdmNMqmpGu20", 
    account: "my account", 
    username: "user1"
}

let data = '';
//params._method = "PUT";
//params._token = document.getElementsByTagName('input').item(name="_token").value;

for(let property in params){
    data += property + '=' + params[property] + '&'; 
}

data = data.slice(0, -1);

console.log(data);
// _method=PUT&_token=uq1Ipn0ehw9Ias5vsgy1pT3ckq4OhdmNMqmpGu20
// &account=my account&username=user1

var xhr = new XMLHttpRequest();
xhr.open('POST', '/personals/' + this.value, true);
// this.value will give the id of the row that will be update.eg. 1  
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
  console.log(this.responseText);
}

xhr.send(data);



via Chebli Mohamed

"No message" error laravel - trying to update user account information

I'm receiving the error "MethodNotAllowedHttpException No message" on submit of my user's form, which is meant to update the user's table. I have two post forms on the same page and two post routes, would that have something to do with it?

I will include all the routes and another form that might be conflicting with it.

web.php

Route::get('profile','userController@profile');
Route::post('profile', 'userController@update_avatar');
Route::post('profile-update', 'userController@update_account'); //this ones not working

userController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use Auth;

use Image;

class UserController extends Controller
{
    //
    public function profile()
    {
        return view('profile', array('user' => Auth::user()) );
    }

    public function update_avatar(Request $request)
    {
        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300,300)->save( public_path('/uploads/avatars/' . $filename) );

            $user = Auth::user();
            $user->avatar = $filename;
            $user->save();

        }
        return view('profile', array('user' => Auth::user()) );
    }

    public function update_account(Request $request, $id) //the function with the error
    {

         User::update([ 
                'id' => Auth::user()->id,
                'name' => $request->name,
                'email' => $request->email
            ]);
            return redirect('/profile');

    }
}

profile.blade.php

 <img src="/uploads/avatars/" style="width:150px;height:150px;float:left;border-radius:50%;margin-right:25px">    
                <h2>'s Profile</h2>

                <form enctype="multipart/form-data" action="/profile" method="post">
                    <label>Update Profile Image</label>
                    <input type="file" name="avatar">
                    <input type="hidden" name="_token" value="">

                    <input type="submit" class=" btn btn-sm btn-light" style="color:#2b2b2b;" value="Update Image">
                </form>

                <form method="post" action="/profile-update"> <!-- The form with the error -->
                    
                    
                    <input type="hidden" name="_method" value="PUT" />
                    <label>Username</label>
                    <input type="text" name="name" class="form-control" value="">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="">
                    <input type="submit" id="update-account" class="btn btn-success" value="Update">

                </form>



via Chebli Mohamed

How can get a matched data from another table using Eloquent?

I would like to display product number, product name and procut detail.

I can display "product number" as below code that is ($pn) I would like to bring "product name" and "product detatil" data which only mache to ($pnum) below foreach loop.

Another table name is "pn_list". table A $pn and table B $pnum should be maches then displya table B's product name is $pname product detail is $pdetail shows up.

blade file (pn is product number)

@foreach  ($pns as $pnx) 
,
@endforeach   

Controller

 public function countpn(Request $request)
    {   $pns = Tablea::select('pn', DB::raw('COUNT(pn) count'))
            ->groupBy('pn')
            ->get();

    return view('pn.index')->with('pns',$pns);
    }

Sorry I have no idea how to combine 2nd table and matching rule so I didn'T make code.



via Chebli Mohamed

Why my detach() and delete() don't work?

I'm working with Laravel 5 and I'm trying to delete some data from database

HTML

<form method="post" action="">
    
    
    <button type="submit" class="btn btn-danger btn-sm" dusk="btn-confirmDeletePub">Yes, Delete</button>
</form>

web.php

Route::resource('publications','PublicationController');

Publication.php (Model)

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

public function topics()
{
    return $this->belongsToMany('App\Topic', 'topic_publication');
}

public function authors()
{
    return $this->belongsToMany('App\Author', 'author_publication');
}

public function details()
{
        /*
        Since we must join the publications table with one of the
        journals/conference/editorship table (based on type column' value)
        to retrieve publication'details,  we "aggregate" the 3 alternatives in this method.

        this method is useful for retrieving from db, 
        for insertions, the 3 methods above ( journal(),conference(),editorship())
        should be used
        */
        switch ($this->type) {
            case 'journal':
                return $this->hasOne('App\Journal');
                break;

            case 'conference':
                return $this->hasOne('App\Conference');
                break;

            case 'editorship':
                return $this->hasOne('App\Editorship');
                break;

        }
 }

PublicationController.php

public function destroy($id)
{
    $publication = Publication::find($id);
    $publication->users()->detach($publication->id);
    $publication->topics()->detach($publication->id);
    $publication->authors()->detach($publication->id);
    //dd($publication);
    $publication->details()->delete();

    //$publication->delete();

    //Redirect('/users')->with('success', 'Publication deleted correctly.');

    return redirect('/users')->with('success', 'Publication deleted correctly.');

}

When I click on the Yes, Delete button in the HTML form, it calls the destroy method in PublicationController to delete the Publication with the specific id. I tried to comment all the code and leave only the return redirect to see if the method is called, and it works. After that, I removed the comments to the detach() functions, but inexplicably in the database they don't produce any results. Finally, I removed the comment at the $publication->details()->delete(); and my application crashes.



via Chebli Mohamed

Laravel: Catch all nonexistent pages

I want to make a 404 page for all nonexistent pages. For example I have this code

public function category($category)
    {
        $category = Category::find($category);
        if($category === null) return abort(404); // return 404 page with 404 header status error
        return view('pages.category', compact('category'));
    }

My routes file

Route::get('/category/{category}', 'CategoryController@category');

I have another components like subcategories, articles, reviews and etc. In first case I can type app/category/1234.
If my app doesn't have category where id = 1234 in category table then without checking variable === null I can get a default but empty page and it will be with a 200 http status. It's not normal.

I can check for null in all components but I think it's not correct.

And one more question about SQL error. "id" field have integer type and if I go to app/category/1sdsds in browser I will get

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer

How can I fix it?

Thanks!



via Chebli Mohamed

Call to a member function method-name on null

I'm calling a method but i'm getting the error

Call to a member function addTenancy() on null

Now, it is null, that is fine. But I need the method to be accessed, as it provides an add button, which is then populate the database.

The method is defined in my Tenancy Model

 public function addTenancy()
    {
        return $this->accepted == 0 && $this->request_sent == 0;
    }

This is the index view.

@if(Auth::user()->id == $tenancy->tenant_id)
            <h1>You cannot add yourself</h1>
          @elseif($Tenancy->addTenancy())
            <a href="/account/tenancy//create" class="btn btn-primary">Start Tenancy</a>
          @endif

This is the controller which renders the view, and passes the $Tenancy variable.

public function index($id){

   $user = User::where('id', $id)->first();

   $Tenancy = Tenancy::first();
   $tenancy =  DB::table('tenancy')->first();

  return view('/pages/account/index', compact(''user', 'Tenancy', 'tenancy'));
}

How do I access the button, even if the DB is null



via Chebli Mohamed

How to show values without column name in laravel

I want to display Values and hide Column Names.

Here is my UserProfileView.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserProfileView extends Model
{
    protected $dates = ['created_at'];
    
    protected $hidden = ['id', 'user_id', 'ip', 'updated_at'];
        
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Here is my User.php

 public function views()
    {
        return $this->hasOne('App\UserProfileView');
    }

Finally in profile.blade.php

<h5>Register Date</h5>
<h5 class="highlight"></h5>

And I get this: Register Date {"created_at":"2018-04-18 22:18:39"} How can I only show the date and nothing else? I think this has something to do with Eloquent but I'm not sure.

Cheers! (Sorry for using snipped)



via Chebli Mohamed

Consume multiple messages in one Job using Supervisor

I have Laravel app and using Supervisor to handle queues. Right now, all my Jobs (workers) consume single message and are set as daemons. It works great.

Now I wanna know how to set a Job to be able to consume multiple messages (bulk) and if no message came for X seconds or max messages it will handle whatever piled up within the Job itself.

Unfortunately, in Laravel docs there is no explanation how to do that so I'm not even sure it's possible..



via Chebli Mohamed

Calling methods in views, that are defined in model. not working

I had a lot of my logic in my views. I refactored this into methods in one of my models. They're being recognized, but not actually working as the IF doesn't change, as the database changes, to reflect a different method that should be called.

For example, my code was originally like this, with all the logic in the views.

@if($tenancy == null || $tenancy->accepted == 0 && $tenancy->request_sent != 1)
              <a href="/account/tenancy//create" class="btn btn-primary">Start Tenancy</a>
            @endif


          <!-- 
            If the user signed in isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->

        @if(Auth::user()->id == $user->id)
          <!-- 
            If the request has been sent but hasn't been accepted.
            Give the option to accept and reject.
            This updates the values in DB.
          -->
          @if($tenancy != null && $tenancy->accepted == 0 && $tenancy->request_sent == 1)
            <form method="POST" action="/account/tenancy//accept">
              
              <input type="submit" class="btn btn-primary" value="Accept Request">
            </form>
            <form method="POST" action="/account/tenancy//reject">
              
              <input type="submit" class="btn btn-warning" value="Reject Request">
            </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
          @elseif($tenancy != null && $tenancy->accepted == 1 && $tenancy->request_sent == 0)
            <form method="POST" action="/account/tenancy//end">
              
              <input type="submit" class="btn btn-primary" value="End Tenancy">
            </form>
            <h5>Currently in Tenancy with </h5>
            <h5>Your property is </h5>
          @endif <!-- End of current user vs this user-->
        @endif <!-- Initial If-->

I then refactored it to this, using method names instead of logc. The methods are defined in my Tenancy controller.

@if(Auth::user()->id == $tenancy->tenant_id)
          <h1>You cannot add yourself</h1>
        @elseif($Tenancy->addTenancy())
          <a href="/account/tenancy//create" class="btn btn-primary">Start Tenancy</a>

    @endif

      <!-- 
        If the user signed in isn't the owner of this profile.
        Do not show these buttons that control accept/reject/end
      -->

    @if(Auth::user()->id == $user->id)
      <!-- 
        If the request has been sent but hasn't been accepted.
        Give the option to accept and reject.
        This updates the values in DB.
      -->
      @if($Tenancy->hasRequestPending())
        <form method="POST" action="/account/tenancy//accept">
          
          <input type="submit" class="btn btn-primary" value="Accept Request">
        </form>
        <form method="POST" action="/account/tenancy//reject">
          
          <input type="submit" class="btn btn-warning" value="Reject Request">
        </form>
          <!-- 
            If the request has been accepted.
            Show button to end the tenancy,
            and property details
          -->
      @elseif($Tenancy->inTenancy())
        <form method="POST" action="/account/tenancy//end">
          
          <input type="submit" class="btn btn-primary" value="End Tenancy">
        </form>
        <h5>Currently in Tenancy with </h5>
        <h5>Your property is </h5>
      @endif <!-- End of current user vs this user-->
    @endif <!-- Initial If-->

This is the controller which renders the view above

  public function index($id){

   $user = User::where('id', $id)->first();
   $users = Auth::user();
   $Tenancy = new Tenancy;
   $tenancy =  DB::table('tenancy')->first();

  return view('/pages/account/index', compact('user', 'users', 'Tenancy', 'tenancy'));
}

This is the Tenancy model where the methods are defined.

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

public function hasRequestPending()
{
    return $this->accepted == 0 && $this->request_sent == 1;
}

public function inTenancy()
{
    return $this->accepted == 1 && $this->request_sent == 0;
}

I can't see why the newly update view shouldn't be moving through the IF statement as the database changes. Any ideas?



via Chebli Mohamed

Issue updating user account with avatar laravel

So I was able to submit the form to allow an avatar to be uploaded and changed which worked. Now I am trying to allow all the user details to be updated too.

If I just try to change the username or email and submit, the page is reloaded with the original content. When I upload a new avatar and then try to submit I get the error "Non-static method Illuminate\Http\Request::input() should not be called statically".

web.php

Route::get('profile','userController@profile');
Route::post('profile', 'userController@update_avatar');

userController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Auth;

use Image;

class UserController extends Controller
{
    //
    public function profile()
    {
        return view('profile', array('user' => Auth::user()) );
    }

    public function update_avatar(Request $request)
    {
        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300,300)->save( public_path('/uploads/avatars/' . $filename) );

            $user = Auth::user();
            $user->avatar = $filename;
            $user->name = Request::input('username');
            $user->email = Request::input('email');
            $user->save();

        }
        return view('profile', array('user' => Auth::user()) );
    }
}

profile.blade.php

<img src="/uploads/avatars/" style="width:150px;height:150px;float:left;border-radius:50%;margin-right:25px">    
                <h2>'s Profile</h2>

                <form enctype="multipart/form-data" action="/profile" method="post">
                    <label>Update Profile Image</label>
                    <input type="file" name="avatar">
                    <input type="hidden" name="_token" value="">

                    <label>Username</label>
                    <input type="text" name="username" class="form-control" value="">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="">

                    <input type="submit" class=" btn btn-sm btn-light" style="color:#2b2b2b;">
                </form>



via Chebli Mohamed

Cannot get data from json_encoded array

i have key and value datas. key is an array. i want to foreach this key data. I use laravel 5. my json_encoded array like :

Collection {#1288 ▼
  #items: array:4 [
    "{"id":1,"title":"abc","path":"abc-path"}" => 19
  ]
}

But i can not fetch key data like i wanted my code :

@foreach($trendings as $key => $value)

 

@endforeach

it gives ' Trying to get property of non-object ' error. but if write code like :

 @foreach($trendings as $key => $value)

     

   @endforeach

it gives me

{"id":1,"title":"abc","path":"abc-path"}

but i want them use in my html. how can i fetch them ?



via Chebli Mohamed

php error with woocommerce Rest api

I am trying to add place order in woocommerce with rest api but showing me following error.

(1/1) HttpClientException cURL Error: Operation timed out after 15000 milliseconds with 0 bytes received.

language : php Framework : laravel

I tried increasing my local php script execution type but it is not working.



via Chebli Mohamed

Error when input date on laravel 5.4

i have using laravel to create prject. But i get some issue when creating a form that using date. Error unknown updated_at

Is there something missing in the table or script? Here the table Table

Here the controller

public function index(Request $request){
    $data = array();
    if($request->isMethod('post') == "post"){
        $pendaftar = new PendaftarModel();
        $pendaftar->tgl             =$request->input(['date']);
        $pendaftar->nopol           =$request->input('no polisi');
        $pendaftar->motor           =$request->input('jenis service');
        $pendaftar->servis          =$request->input('keluhan kendaraan');
        $pendaftar->keluhan         =$request->input('keluhan kendaraan');
        // $pendaftar->keluhan      =$request->input('keluhan kendaraan');

            if($pendaftar->save()){
                $data["status"]  = "success";
                $data["message"] = "Selamat, booking berhasil. Staff kami akan segera menghubungi anda untuk penjadwalan";
            }else {
                $data["status"]  = "danger";
                $data["message"] = "Maaf, Booking Gagal";
            }
    }
    return view("daftar", $data);

The view blade

div class="well well-lg">
    <div class="container">
        <h2>Booking Online</h2>
        <span>Halaman untuk melakukan pendaftaran kendaraan.</span>
    </div>
</div>

<div class="container">

    <div class="alert alert-info">
        <i class="glyphicon glyphicon-info-sign"></i> Silahkan isi data berikut
    </div>
    <div class="panel panel-primary">

        <div class="panel-heading">
            Form Data Kendaraan
        </div>
        <div class="panel-body">

            @if(isset($status))
            <div class="alert alert-<?php echo $status; ?>">
                <?php echo $message; ?>
            </div>
            @endif

            <form method="post">
                

            <div class="form-group">
                 <label for="tanggal">Pilih Tanggal</label>
                 <input class="form-control" id="tanggal" required type="date" name="tgl" max="3000-12-31" 
                        min="1000-01-01" placeholder="Pilih Tanggal">
            </div>

            <div class="form-group">
                <label for="nopol">Nomor Polisi:</label>
                <input class="form-control" id="nopol" required type="text" name="nopol" placeholder="Masukkan No Polisi">
            </div>

            <div class="form-group">
                <label for="motor">Jenis Motor:</label>
                <input class="form-control" id="motor" required type="text" name="motor" placeholder="Matic/Bebek/Sport">
            </div>

            <div class="form-group">
                <label for="servis">Tipe Service:</label>
                <input class="form-control" id="servis" required type="text" name="servis" placeholder="Besar/Kecils">
            </div>



            <div class="form-group">
                <label for="keluhan">Keluhan Kendaraan:</label>
                <textarea name="keluhan" id="keluhan" required class="form-control" rows="5" placeholder="Tulis Keluhan Motor Anda"></textarea>
            </div>

            <button type="submit" name="submit" class="btn btn-success btn-lg"><i class="glyphicon glyphicon-send"></i> Submit</button>
                <button type="reset" class="btn btn-danger btn-lg">Reset</button>
            </form>
        </div>
    </div>

</div>

The Model

{
//
protected $table = "pendaftar";
public $timestamps = true;
protected $fillable=['tgl','nopol','motor','servis','keluhan'];

}

Please help me to fix this, any comment will appreciate.

Bestly Regards



via Chebli Mohamed

Bootstrap modal form not submitted

I was trying to submit form which is inside a modal.The modal will come dynamically.

<a href="#" data-toggle="modal"  id="getProduct" data-url="" data-target="#modal-quickview">

Here is the Modal form which will store the data

{!! Form::open(['method' => 'POST','class'=>'contact_dialog','route' => 'storeCart', 'enctype'=>'multipart/form-data']) !!}
  {!! Form::token(); !!}
    @if($product->category_id == '1')
            <div class="product-color-size-area">
              <div class="color-area">
                <h2 class="saider-bar-title">Color</h2>
                <div class="color">
                  <select class="single-option-selector" name="color">
                    @foreach($colors as $color)
                      <option value=""></option>                    
                    @endforeach
                  </select>
                </div>
              </div>
              <div class="size-area">
                <h2 class="saider-bar-title">Size</h2>
                <div class="size">
                  <select class="single-option-selector" name="size">
                     @foreach($sizes as $size)
                      <option value=""></option>                     
                    @endforeach
                  </select>
                </div>
              </div>
            </div>
    @endif    

     @if($product->category_id == '3')
            <div class="product-color-size-area">
              <div class="size-area">
                <h2 class="saider-bar-title">Size</h2>
                <div class="size">
                  <select class="single-option-selector" name="frame_size">
                     @foreach($frame_sizes as $frame_size)
                      <option value=""></option>                     
                    @endforeach
                  </select>
                </div>
              </div>
            </div>
    @endif 

     @if($product->category_id == '4')
            <div class="product-color-size-area">
              <div class="size-area">
                <h2 class="saider-bar-title">Size</h2>
                <div class="size">
                  <select class="single-option-selector" name="shoe_size">
                     @foreach($shoe_sizes as $shoe_size)
                      <option value=""></option>                     
                    @endforeach
                  </select>
                </div>
              </div>
            </div>
    @endif   

    <input type="hidden" name="product_name" value="">       
            <div class="product-variation">

                <div class="cart-plus-minus">
                  <label for="qty">Quantity:</label>
                  <div class="numbers-row">
                    <div onClick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty ) &amp;&amp; qty &gt; 0 ) result.value--;return false;" class="dec qtybutton"><i class="fa fa-minus">&nbsp;</i></div>
                    <input type="text" class="qty" title="Qty" value="1" maxlength="12" id="qty" name="quantity">
                    <div onClick="var result = document.getElementById('qty'); var qty = result.value; if( !isNaN( qty )) result.value++;return false;" class="inc qtybutton"><i class="fa fa-plus">&nbsp;</i></div>
                  </div>
                </div>
                <button  class="button pro-add-to-cart submitForm" title="Add to Cart" type="submit"><span><i class="fa fa-shopping-cart"></i> Add to Cart</span></button>             
            </div>
    {!! Form::close() !!}

The problem here is when i tried to submit the data it doesn't call the route means nothing happened. What could be possible reason for form not submitting?



via Chebli Mohamed

samedi 28 avril 2018

how to completely logout in laravel 5.5 controller?

After I logout of my laravel application, in the browser I press the button to backward (go back) and then I see the dashboard.

I want to eliminate this "session" that laravel mantein if I go back, (btw; when In that dashboard when I click other URL the middleware redirect me to the login view)

can anyone help me?

my route ->

Route::get('auth/logout', 'Auth\LoginController@logout')->name('logout');

my controller ->

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;


class LoginController extends Controller
{
    private $user;


    public function logout(){
        Auth::logout();
        \Session::flash('success',"logout");
        return redirect()->route('login');
    }

}



via Chebli Mohamed

Model relationship creation uses the wrong field in Laravel

I want to create a new model using the relationship between a two model module and chapter and they have HasMany relationship between them as follow :

//Module mode
public function chapters()
{
    return $this->hasMany(Chapter::class, 'module_slug', 'slug');
}

//Chapters Model
public function module()
{
    return $this->belongsTo(Module::class, 'module_slug', 'slug');
}

And here's how I'm storing the models :

    $module = Module::create([
        'title' => $request->module_title,
        'icon' => $request->module_title
    ]);

    $module->chapters()->create([
        'pdf_url' => $path,
        'title' => $request->chapter_title
    ]);

The Issue :

The problem I got is that the $module->chapters()->create() is using the id not the slug which I'm specifying as the primary key like this :

//Module model
protected $primaryKey = 'slug';
protected $keyType = 'string';


//Chapters model
protected $primaryKey = 'slug';
protected $keyType = 'string';

I don't know why it uses the id field like this screenshot :

The issue



via Chebli Mohamed

How to Foreach loop through Laravel collection.?

i m a beginner at laravel. using 5.5 . i have this collection return by my controller :

$products = Product::with('bazar.resellers')->take(2)->get();
dd($products);
//return view('shop.index')->with('products', $products);

which basically is three tables with nested relations. Note the relations lists in the code below. i want to access data(all columns in red colour) from every model i have in the collection i.e. Product, bazar and reseller.

Relationships are quite fine. but how to retrieve it from a collection? i dunno how foreach loops play with a collection.

Collection {#578 ▼
#items: array:2 [▼
0 => Product {#487 ▼
  #fillable: array:7 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:10 [▼
    "id" => 1
    "created_at" => "2018-04-27 12:54:41"
    "updated_at" => "2018-04-27 12:54:41"
    "imgp" => "shirt.jpg"
    "title" => "shirt1"
    "Prod_descript" => "shirt1 is a good shirt"
    "price" => 10
    "reseller_id" => 1
    "City_id" => 1
    "bazar_id" => 1
  ]
  #original: array:10 [▶]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:1 [▼
    "bazar" => Bazar {#523 ▼
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 1
        "Bazarname" => "Saddar"
        "Bazarlat" => null
        "Bazarlong" => null
        "created_at" => null
        "updated_at" => null
        "City_id" => 1
      ]
      #original: array:7 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "resellers" => Collection {#574 ▼
          #items: array:1 [▼
            0 => Reseller {#564 ▼
              #guard: "reseller"
              #fillable: array:12 [▶]
              #hidden: array:2 [▶]
              #connection: "mysql"
              #table: null
              #primaryKey: "id"
              #keyType: "int"
              +incrementing: true
              #with: []
              #withCount: []
              #perPage: 15
              +exists: true
              +wasRecentlyCreated: false
              #attributes: array:15 [▼
                "id" => 1
                "Fname" => "talha"
                "Lname" => "ali"
                "email" => "p@g.com"
                "password" => "$2y$10$M7wOmSouxSAYADN7NeFdSObT8fGwkEOFxVmOgcNSWvrixWCDtA/1S"
                "mobile_no" => "03169880008"
                "landline_no" => "0987654"
                "shop_name" => "MyTestSHop"
                "NIC_no" => "170178359437589754"
                "shop_address" => "University Town, Peshawar, Pakistan"
                "remember_token" => "wrb3nOwOWQcTuoF0P9KnaknwpOxfpTHt4gkShUmTzkR2Df9A7pPY5shBq6pQ"
                "created_at" => "2018-04-27 12:42:25"
                "updated_at" => "2018-04-27 12:42:25"
                "City_id" => 1
                "bazar_id" => 1
              ]
              #original: array:15 [▶]
              #changes: []
              #casts: []
              #dates: []
              #dateFormat: null
              #appends: []
              #dispatchesEvents: []
              #observables: []
              #relations: []
              #touches: []
              +timestamps: true
              #visible: []
              #guarded: array:1 [▶]
              #rememberTokenName: "remember_token"
            }
          ]
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}
1 => Product {#488 ▶}
]
}

the code i have tried is not working!

@foreach($products as $product)
<h1></h1>

@foreach($product->bazar as $bazar)
    <h3></h3>

    @foreach($bazar->resellers as $reseller)
        <p></p>
    @endforeach

@endforeach

@endforeach



via Chebli Mohamed

Auto close Alert bootstrap

Hi I´am using Laravel version 5.6 with Bootstrap 4 and I make an Alert message on the page. It already show, and close. But I can't make it auto close with the setTimeout function.

Thats the auto close code that doesn't work

enter image description here

Some one Knows what is happening?



via Chebli Mohamed

Laravel use view while sending email from Gmail API

I am trying to send emails using Gmail API. It worked fine if I use raw body, but I am unable to figure out how to use Laravel Views as the body when sending the email from Gmail API . Or use Gmail API to send using Laravel Mail Here is my code:

        $strSubject = 'Test mail using GMail API';
        $strRawMessage = "To: Someone <someone@domain.com>\r\n";
        $strRawMessage .= 'Subject: =?utf-8?B?' . base64_encode($strSubject) . "?=\r\n";
        $strRawMessage .= "MIME-Version: 1.0\r\n";
        $strRawMessage .= "Content-Type: text/html; charset=utf-8\r\n";
        $strRawMessage .= 'Content-Transfer-Encoding: quoted-printable' . "\r\n\r\n";
        $strRawMessage .= "this is body";
        $service = new Google_Service_Gmail($client);

        try{
            $mime = rtrim(strtr(base64_encode($strRawMessage), '+/', '-_'), '=');
            $msg = new Google_Service_Gmail_Message($client);

            $msg->setRaw($mime);
            $service->users_messages->send("me", $msg);

        }
        catch(Exception $e){
            \Log::info($e->getMessage());

        }



via Chebli Mohamed

Laravel eloquent: Multiply two columns of two different tables and display

Carts table columns :

    'id',
    'user_id',
    'sp_id',
    'service_id',
    'dryclean',
    'q_Shirt',
    'q_Pant',
    'q_Tie'

Pricing table column :

'id'
'sp_id'
'Shirt'
'Pant'
'Tie'

Both table do not have any relationship defined.

In cart controller

public function cart($sp_id, $service_id)
    {
     $prices = DB::table('pricings')->where('pricings.sp_id', '=', $sp_id)->get();
     $cart = DB::table('carts')->where('carts.service_id', '=' , $service_id)->where('carts.sp_id','=', $sp_id)->where('user_id', '=' , auth()->id())->orderBy('id', 'desc')->take(1)->get();
     return view('user.cart')->with('prices', $prices)->with('cart', $cart);
    }

How do I calculate total amount of order?

If column dryclean has value of none then total is 0. else total will be

(
carts->q_Shirt*prices->Shirt +
carts->q_Pant*prices->Pant +
carts->q_Tie*prices->Tie
) 

This code is just for understanding of how I am calculating total

Please help me write code in laravel controller to calculate total and how to display it in view.



via Chebli Mohamed

Admin log in Laravel - redirecting to user login page

Im trying to set up multiple authentication, and have a login for admins as well as users. I followed part 1 and got two half way through of part 2 of this tutorial https://www.youtube.com/watch?v=gpACQXVX2kA&t=32s. When I try to log in as an admin, it redirects to /login (users login page) when I have it set to redirect to /admin/home.

It is redirecting like that because the admin login details are not correct? I set up the admin details through the database but in the video it says to copy and paste the encrypted password from the users table, so I did, and used the same password as that user to sign in.

I watched the video over and over again for any mistakes following along, but I don't think I done anything differently.

There is a lot of files I created and edited to try get this to work, so If you need to see anymore please let me know.

web.php

Route::get('admin/home','AdminController@index');
Route::get('admin','Admin\LoginController@showLoginForm')->name('admin.login');
Route::post('admin','Admin\LoginController@login');
Route::post('admin-password/email','Admin\ForgotPasswordController@sendResetLinkEmail')->name('admin.password.email');
Route::get('admin-password/reset','Admin\ForgotPasswordController@showLinkRequestForm')->name('admin.password.request');
Route::post('admin-password/reset','Admin\ResetPasswordController@reset');
Route::get('admin-password/reset/{token}','Admin\ResetPasswordController@showResetForm')->name('admin.password.reset');

AdminController

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    public function index()
    {
        return view('admin.home');
    }
}

admin.php

<?php

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

class Admin extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

LoginController

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = 'admin/home'; //user redirects to /routes


    public function __construct()
    {
        $this->middleware('guest:admin', ['except' => 'logout']); 
    }

    public function showLoginForm()
    {
        return view('admin.login');
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }
}

Login.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Admin Login</div>

                <div class="panel-body">
                    <form class="form-horizontal" method="POST" action="">
                        

                        <div class="form-group">
                            <label for="email" class="col-md-4 control-label">E-Mail Address</label>

                            <div class="col-md-6">
                                <input id="email" type="email" class="form-control" name="email" value="" required autofocus>

                                @if ($errors->has('email'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="col-md-4 control-label">Password</label>

                            <div class="col-md-6">
                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))
                                    <span class="help-block">
                                        <strong></strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox" name="remember" > Remember Me
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-8 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Login
                                </button>

                                <a class="btn btn-link" href="">
                                    Forgot Your Password?
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Database structure database-structure

Database content (copied password) database-content



via Chebli Mohamed

Laravel migration cancel column as nullable

I created a migration with user_id column making nullable. How can I change user_id as not nullable? My previous migration code is given below:

Schema::table('users', function($table)
{
    $table->string('name', 50)->nullable();
});



via Chebli Mohamed

Method in model doesn't seem to be being recognised in view

I was tidying up my code. Instead of having my logic all in the views, I broke it off into functions in the Tenancy model, and called them in the view.

For example

This was my original line in index.blade.php

@if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)

I changed it to this

@if($Tenancy->addTenancy()

And moved the logic to my Tenancy model like so

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

This works for adding a user.

But for detecting requests, and detecting friends it is not working. The IF is't progressing past the first if.else block

 @if(Auth::user()->id == $user->id)
          <h1>You cannot add yourself</h1>
        @elseif($Tenancy->addTenancy())
          <a href="/account/tenancy//create" class="btn btn-primary">Start Tenancy</a>
        @endif

          <!-- 
            If the user signed in, isn't the owner of this profile.
            Do not show these buttons that control accept/reject/end
          -->

        @if(Auth::user()->id == $user->id)
          <!-- 
            If the request has been sent, but hasn't been accepted.
            Give option to accept and reject.
            This updates the values in DB.
          -->
          @if($Tenancy->hasRequestPending())
            <form method="POST" action="/account/tenancy//accept">
              
              <input type="submit" class="btn btn-primary" value="Accept Request">
            </form>
            <form method="POST" action="/account/tenancy//reject">
              
              <input type="submit" class="btn btn-warning" value="Reject Request">
            </form>
              <!-- 
                If the request has been accepted.
                Show button to end the tenancy,
                and property details
              -->
          @elseif($Tenancy->isTenancy())
            <form method="POST" action="/account/tenancy//end">
              
              <input type="submit" class="btn btn-primary" value="End Tenancy">
            </form>
            <h5>Currently in Tenancy with </h5>
            <h5>Your property is </h5>
          @endif <!-- End of current user vs this user-->
        @endif <!-- Initial If-->

Correlating functions in Tenancy Model

public function hasRequestPending()
    {
        return $this->accepted == 0 && $this->request_sent == 1;
    }

    public function inTenancy()
    {
        return $this->accepted == 1 && $this->request_sent == 0;
    }



via Chebli Mohamed

Auth::login doesnt work

I want to modify the login compartment of laravel, I want to do everything the same without encrypting the password.

This is the model:

class User extends Authenticatable
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array*/

protected $fillable = [
    'id','nombre', 'apellido1', 'apellido2',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

protected $table = 'usuario';
}

I modify LoginController overwritten the login function:

  public function login(Request $request)
 {
    $this->validateLogin($request);

    $email = $request->get('email');
    $pass = $request->get('password');

    $matchWhere = ['email' => $email, 'password' => $pass];

    $user = User::where($matchWhere)->first();

    if ($user ) {
        Auth::guard('usuarios')->login($user);

        return redirect()->intended('/home');
    } else {
        return $this->sendFailedLoginResponse($request);
    }
}

And I create the specific guard in auth.php:

 guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],

    'usuarios' => [
        'driver' => 'session',
        'provider' => 'usuarios',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],

    'usuarios' => [
        'driver' => 'database',
        'table' => 'usuario',
    ],
],

Finally I modify the app.blade.php using my own guard:

@if (Auth::guard('usuarios')->guest())
 <li><a href="">Login</a></li>
 <li><a href="">Register</a></li>
@else
  -- logout
@endif

Why doesn't work? I modified the provider to eloquent and change the model. I try to use the default provider



via Chebli Mohamed

Attempting to clean up code -> errorexception must return a relationship instance

I'm trying to clean up code in my view so removing the logic, and calling a method instead.

This was my original line in index.blade.php

@if($Tenancy->accepted == 0 && $Tenancy->request_sent != 1)

I changed it to this

@elseif($Tenancy->addTenancy)

And moved the logic to my Tenancy model like so

public function addTenancy()
{
    return $this->accepted == 0 && $this->request_sent == 0;
}

I'm not looking for a relationship. Any idea about this error.



via Chebli Mohamed

Laravel/Angular 5/GoDaddy - All Image Paths Are Broke and Cannot Be Displayed

I'm working with a project that is using Laravel (api) and Angular 5 (front-end) on GoDaddy. In order to use Laravel safely on GoDaddy, I had to put all the Laravel files one directory back from public_html and all the Angular files in public_html. In order for this to work properly, I had to move the Laravel public folder to public_html and point to the Laravel file's via an absolute path. Everything is working so I know I'm headed in the right direction.

Laravel path - /home/website/laravel/

Public path - /home/website/public_html/

The only problem I'm having is trying to serve-up images for an image gallery. I store all the images in Laravel's storage directory and save the image path's in the db. When it's time to load all the images via Angular, I call the api and it returns all the image name's in a collection and Angular appends the path. Here's an example - https://website.com/storage/media/events/1/m_22721a76-8f0a-4ce2-97a5-e5ac169127a5.jpg.

Since my images are kept one directory back from public_html, they cannot be reached and are broke. My first thought is to save all the images in a directory in public_html, but I'm not sure if I can change Laravel's filesystems config to allow that. I also thought about trying to use .htaccess to detect a certain path and redirect, but I couldn't get it to work. I feel like using Laravel's filesystems is the way to go, but couldn't get it to work, here is what I came up with:

filesystems.php

'public' => [
    'driver' => 'production',
    'root' => storage_path('/home/website/public_html/storage/media/'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],

ImageGalleryController.php

if(App::environment('local'))
{
    Storage::disk('local')->put('events' . '/' . $id . '/t_' . $path, (string) $thumb->encode());
}
else if(App::environment('test')) 
{
    Storage::disk('test')->put('events' . '/' . $id . '/t_' . $path, (string) $thumb->encode());
}
else {
    Storage::disk('production')->put('events' . '/' . $id . '/t_' . $path, (string) $thumb->encode());
} 

With my current file setup, any ideas how I can display images from Laravel's storage directory?



via Chebli Mohamed

How do I know if my route is reached?

I'm working with Laravel 5 and I'm trying to call the destroy function inside my Controller

HTML

<div class="modal fade" id="deletePub" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true">
   <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h6 class="modal-title" id="modalPublicationTitle">Confirm Publication Delete</h6>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">    
                <form id="msform" action="" method="post">
                    
                        
                    <div class="row align-items-center">
                        <div class="col-lg-12" align="center">Really, do you want to delete this publication?</div>
                       <button type="button" class="btn btn-danger btn-sm" id="btn-confirmDeletePub">Yes, Delete </button> 
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

JS

$(document).ready(function() {
    $("#btn-confirmDeletePub").click(function(){

        $.ajaxSetup({
            headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')  
            }
        });

        var publicationId = window.location.href.split("/")[4]

        console.log(publicationId);

        $.ajax({
            type: "POST",
            url: "/publications/" + publicationId,
            data: {_method: 'delete'},
            //contentType: "application/json; charset=utf-8",
            //dataType: "json",
        });
    });
});

web.php

Route::resource('publications','PublicationController');

PublicationController.php

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $publication = Publication::find($id);
    dd($publication);
    $publication->users()->detach($publication->id);
    $publication->topics()->detach($publication->id);
    $publication->authors()->detach($publication->id);

    $publication->details()->delete();

    //$publication->delete();

    Redirect('/users')->with('success', 'Publication deleted correctly.');

}

the html code calls the btn-confirmDeletePub function of the JS file when I click on the Yes, delete button. The JS button captures the id of the publication to be deleted and will sent to the destroy($id) function of the PublicationController, but I don't have the certainty that the method is called. I tried to put a dd($ publication) to print on the Google Chrome's console, but nothing to do. The error I get is: POST http://localhost:8000/publications/4 500 (Internal Server Error).



via Chebli Mohamed

Laravel validate returns "error" instead of "errors"

Using laravel 5.6, I currently, I get a 422 JSON response like this when a validation error occurs using $request->validate($rules):

{
    "error": {
        "isbn": [
            "The isbn field is required."
        ],
        "price": [
            "The price field is required."
        ]
    }
}

Instead, I expect it to be:

{
    "errors": {
        "isbn": [
            "The isbn field is required."
        ],
        "price": [
            "The price field is required."
        ]
    }
}

I noticed that the defaults in the RegisterController do return the plural of error when the validator is called with return Validator::make($data, $rules)...

Why do I get the singular form with $request->validate($rules)?



via Chebli Mohamed

Laravel 5, sometimes loads very slow

I've been with Laravel 5 for a while, I've been doing tests and I have a problem that I do not know about because it occurs.

Sometimes, when I load a page, for example: www.myweb.com/admin Route::any('/admin', "IndexController@indexAdmin");the page loads in a few seconds. However, other times you are accessing this same page, it takes 20 seconds or more to load.

When the page takes time to load, if I click on the button to stop loading the page and I give it to reload page, the same thing happens.

However, if in case the page takes a long time to load, click on the url and press enter, as it would be normal, a few seconds.

When I say that the page is slow to load, I say that the DOM is slow to load, not the photos, videos, etc.

The css background always loads without any problem.

Does anyone know why?

I can not put code because I do not know what code should I put



via Chebli Mohamed

Condition in my view

i have a another problem in my view This condition @if dont work :

@if( ! empty($news))
    <div class="container">
        <div class="row justify-content-center">
            <h1 style="color:#fff;text-decoration:underline;margin-left:20px;">Any News !</h1>
        </div>
    </div>
@else
    <h1 style="color:#fff;text-decoration:underline;margin-left:20px;">Last News :</h1>
    <div class="col-md-8">
        <div class="row">
            @foreach($news as $new)
                <div class="card" style="width: 18rem; margin-left:30px;">
                    <img class="card-img-top img-responsive" style="height:160px;" src="img/.jpg" alt="Card-news-">
                    <div class="card-body">
                        <h5 class="card-title"></h5>
                        <p class="card-text">
                            @if(strlen($new['content'])>150)
                                ...
                            @else
                                
                            @endif
                        </p>
                        <a href="#" class="btn btn-primary">More.</a>
                        @if(@admin)
                            <a href="" class="btn btn-warning">Edit</a></td>
                            <form action="" method="post">
                                @csrf
                                <input name="_method" type="hidden" value="DELETE">
                                <button class="btn btn-danger" type="submit">Delete</button>
                            </form>
                        @endif
                    </div>
                </div>
            @endforeach
        </div>
    </div>
@endif

i would to show Any News ! when don't have news and Last News ! when i have news Can you help me ^^ ?



via Chebli Mohamed

How to get multiple result using Eloquent

I can get first result using this code

public function search(Request $request)
{
    $record = St::where('pn', $request->input)->first();
    $param = ['input' => $request->input, 'record' =>$record];
    return view('contacts.find', $param);

}

but, I changed like this

        $record = St::where('pn', $request->input)->get();

error show up

Method Illuminate\Database\Eloquent\Collection::getData does not exist

Could someone tell me why?

my version is 5.6



via Chebli Mohamed

How to keep previously inserted data if I send blank data while updating through UpdateOrCreate method of Laravel Eloquent?

I am new in Laravel. I am using the UpdateOrCreate method of Laravel and I am trying to update some fields of the form and other fields will be as like as earlier. Let, I have three fields in the form which are user_bio, user_image, user_cover_image. I want to update uer_bio only. I tried various way but I failed. I need to update will fields together! How can I solve this issue?

Here are my codes: profile.blade.php (front-end view):

<div class="card">
                <div class="card-header"> প্রোফাইল </div>
                <div class="card-body">
                    <form action="profile/store" method="post" enctype="multipart/form-data">
                    @csrf
                    
                    <div class="form-group">
                        <label for="user_bio">Bio:</label>
                        <input type="text" class="form-control" id="user_bio" name="user_bio">
                    </div>

                    <div class="form-group">
                        <label>Upload your profile picture:</label>
                        <input type="file" class="form-control" name="profilepicture" id="profilepicture">
                    </div>

                    <div class="form-group">
                        <label>Upload your cover photo:</label>
                        <input type="file" class="form-control" name="coverphoto" id="coverphoto">
                    </div>
                    

                    <button type="submit" class="btn btn-default" name="submit" value="submit">Submit</button>
                    </form>
                </div>
                
            </div>

ProfileController:

/** User Profile Picture (with URL) Storing Process Starts here **/
    $image = $request->file('profilepicture');
    $imagenewname= rand() .'.'. $image-> getClientOriginalExtension();
    $path = $request->file('profilepicture')->storeAs(
        'public/UserImages', $imagenewname
    );

    $imageName = "UserImages/".$imagenewname;
    /** User Profile Picture (with URL) Storing Process Ends here **/


    /** User Cover Photo (with path) Storing Process Starts here **/
    $coverphoto = $request->file('coverphoto');
    $coverphotoname= rand() .'.'. $coverphoto-> getClientOriginalExtension();
    $coverphotopath = $request->file('coverphoto')->storeAs(
        'public/CoverPhotos', $coverphotoname
    );

    $coverPhotoName = "CoverPhotos/".$coverphotoname;
    /** User Cover Photo (with path) Storing Process Ends here **/



    $check = Profile::updateOrCreate(['user_id' => $request->user_id], ['user_bio' => $request->user_bio, 'user_image' => $imageName, 'user_cover_image' => $coverPhotoName]);



via Chebli Mohamed