samedi 31 juillet 2021

Check whether particular product is already added by user in Laravel

I have two table

  1. Menu
  2. Products

there structures are:

Menu:

id | product_id | user_id 

Product:

id | title | price

issue is i want to show add button if product is added in menu table by the specific user and if product is already added then i have to show remove button to remove data from menu table instead of add table.

 $product = Product::where(['user_id'=>$userID])->with('ProductImages')->get();
 $menuPlanner=Menu::where(['user_id'=>auth()->user()->id])->get();  
 $html =  view('frontend.dashboard.menu.available_items', ['products'=>$product,'menu_planner'=>$menuPlanner])->render();
 echo json_encode(array('products' => $html));

Is there any way in laravel to achieve this without any loop in view.



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

Laravel 8 UniSharp File Manager 3 - image uploaded but not showing

When I upload some files with LFM, the images are uploaded in a new folder created in storage/app/public/photos/shares and thumbnails in a nested folder thumbs. BUT the images thumbnails are not showing in the FM, only the filenames under a blank image.

1/ How can I fix that?

2/ Under the images there is a little blue box with number 1 inside . What is that? I can I get rid of it?

3/ I also find strange that the images are stored in a "shared" folder although this is set to false in the /config/lfm.php. Do I have to edit unisharp/laravel-filemanager/src/config/lfm.php as well? Or should I delete the one in /config?

'allow_shared_folder'      => false,
'shared_folder_name'       => 'shares',

4/ I also do not want that location for the upload. Instead I want the images stored in /public/images/uploads and same for the files into /public/files/uploads. Where do I change these paths?



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

Laravel 8 UniSharp File Manager 3 change base directory from app/storage to app/public

I am struggling to change the base directory to upload images to be in app/public instead of the default app/storage.

There is no base_directory in the config/lfm.php file.

I also see that the lfm.php file is in the unisharp/laravel-filemanager/src/config folder. Why is this config file in 2 places?

The reason I need to change to have this structure is that I already have hundreds of images in public/images and files in public/files and I want to keep these links in the existing pages working.

So what do I have to do to change that?



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

Rounded Image Using Laravel Intervetion

I want to Make a rounded corner image in laravel intervention. Please help me out.

enter image description here

$image = Image::make($user['profile_pic'])->fit(300, 300, function ($constraint){
            $constraint->aspectRatio();
            });
            $image->encode('png');
            $width = $image->getWidth();
            $height = $image->getHeight();
            $mask = Image::canvas($width, $height);
        // draw a white circle
            $mask->circle(280, $width / 2, $height / 2, function ($draw) 
           {
                $draw->background('#fff');
            });
            $image->mask($mask, false);
            $img->insert($image, 'top-left', 50, 48);

Make a circle Using the Above code, I want to make in rounded corner Image. Thank you in advance.



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

Migrate Laravel/Vue (laravel-mix) to production

I'm trying to move assets from localhost to production, the problem is that function mix is adding "//localhost:8080" in production, after running npm run production on my local machine.

My master.blade.php:

...
<link rel="stylesheet" href="">
</head>

<body class="">
  <div id="app"></div>

  <script src=""></script>
  <script src=""></script>
  <script src=""></script>
</body>
...

But on localhost is fine after npm run production:

...
<script src="/js/manifest.js?id=d3d86536d111c156f3bf"></script>
<script src="/js/vendor.js?id=4f7200a4a1dcf3c99f20"></script>
<script src="/js/app.js?id=5984cd10858ad9eb49c3"></script>
...

But in production it stays:

<script src="//localhost:8080/js/manifest.js"></script>
<script src="//localhost:8080/js/vendor.js"></script>
<script src="//localhost:8080/js/app.js"></script>

And my .env file:

APP_NAME=Laravel
APP_ENV=production
APP_KEY=base64:iEid8NZ4ponMoI6fitOLyZBoVNOTB4LWzgin6TIsGA0=
APP_DEBUG=true
APP_URL=https://www.my-url.com
...

My steps are:

  1. Execute npm run production (on my local)
  2. Move by FTP the public/js, public/css and mix-manifest.json to production env

My main problem is not knowing how to tell mix function I have already run the production command and how do I make it identify the right files in production (generated with npm run production).



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

Multidimensional array inside foreach loop

I have this Category List where i'm creating menu planner this code is working and the output of this code is given below,

 $categoryList=Category::where('user_id',$id)->get();   
    $meal_day=array('1'=>'Monday','2'=>'Tuesday','3'=>'Wednesday','4'=>'Thursday','5'=>'Friday','6'=>'Saturday','7'=>'Sunday');
    $meal_plan=[];
    $i= 0;
    foreach($categoryList as $catKey => $row)
    {  
        for($k=1;$k<=count($meal_day);$k++)
        {   
            $menuPlanner=MenuPlanner::where(['day'=>$k,'user_id'=>auth()->user()->id,'category_id'=>$row['id']])->first(); 
            if($menuPlanner)
            {
                $product = Product::where(['id'=>$menuPlanner->product_id])->first();
                $meal_plan[$catKey][$k]['product_title']=$product->title;
                
            }
        }
    }

Output:

array:2 [
  0 => array:7 [
    1 => array:1 [
      "product_title" => "Product 1"
    ]
    2 => array:1 [
      "product_title" => ""
    ]
    3 => array:1 [
      "product_title" => ""
    ]
    4 => array:1 [
      "product_title" => ""
    ]
    5 => array:1 [
      "product_title" => ""
    ]
    6 => array:1 [
      "product_title" => ""
    ]
    7 => array:1 [
      "product_title" => ""
    ]
  ]
  1 => array:7 [
    1 => array:1 [
      "product_title" => "Product 2"
    ]
    2 => array:1 [
      "product_title" => ""
    ]
    3 => array:1 [
      "product_title" => ""
    ]
    4 => array:1 [
      "product_title" => ""
    ]
    5 => array:1 [
      "product_title" => ""
    ]
    6 => array:1 [
      "product_title" => ""
    ]
    7 => array:1 [
      "product_title" => ""
    ]
  ]

but i have multiple products in menu planner in the first

 $menuPlanner=MenuPlanner::where(['day'=>$k,'user_id'=>auth()->user()->id,'category_id'=>$row['id']])->get(); 
       
 foreach($menuPlanner as $menuKey => $menurow)
 {
 $product = Product::where(['id'=>$menurow->product_id])->first();
 $meal_plan[$catKey][$k]['product_title']=$product->title;
 }

So how will i store multiple product at array indexes.



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

vendredi 30 juillet 2021

How to add another table after joining multiple tables in Laravel?

I'm trying to achieve the following MySQL query with Laravel

SELECT a.*, b.*, c.* FROM table_1 a LEFT JOIN table_2 b ON a.b_id = b.id, table_3 c WHERE c.age > 21;

I know how to join tables in Laravel. But if you see my SQL query carefully you can find that there is another table just after the left join (without any join). This is where I'm stuck.

I tried the following code in Laravel, but didn't work.

DB::table(DB::raw('table_1 a, table_3 c'))
  ->select('a.*', 'b.*', 'c.*')
  ->leftJoin('table_2 b', 'a.b_id', '=', 'b.id')
  ->where('c.age', '>', 21)
  ->get();

Please help me out with the proper solution. Thanks in advance.

Note: Please ignore syntax error if any



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

Nothing saved when uploading multiple image

i have error array to string when i uploading multiple image. this is my blade code

  <form role="form" action="" method="POST" enctype="multipart/form-data"> 
     <input type="file" class="form-control"  placeholder="Image Gallery" name="image_gallery[]" 
     required="required" multiple>
   </form>

i already put multiple on input tag

and this is the controller code. the commented code "image Gallery" is the code for uploading image gallery

public function store(Request $request)
    {   
        $this->validate($request,[
            'photo'=>'required|image|mimes:png,jpg,jpeg|max:1000',
            'slug'=>'required',
            'name'=>'required',
            'description'=>'required',
            'stock'=>'required|numeric',
            'price'=>'required|numeric',
            'sale_price'=>'required|numeric',
            'brand_id' =>'integer',
            'manufacture_id' =>'integer',
            'genre_id' => 'integer',
            'gudang_id' => 'integer',
            'weight' => 'integer',
            'status' => 'required',
            'date_arrival' => 'required_if:status,==,"preorder',
            'is_protector' => 'nullable',
            'type' => 'nullable',
            'protector_id' =>'required_if:is_protector,==,"1"',
            'image_gallery' => 'required|image|mimes:png,jpg,jpeg|max:1000',
        ]);
        $formInput= $request->except(['_token']);
   
        $file = $request->file('photo');
        $filename = $file->getClientOriginalName();
        $request->file('photo')->move('static/dist/img/',$filename);
        $formInput['photo'] = 'static/dist/img/'.$filename;

        //image Gallery
        if($request->hasFile('image_gallery')){
            foreach ($request->file('image_gallery') as $file_gallery) {
            $name =  $file_gallery->getClientOriginalName();
            $file_gallery->move('static/dist/img/',$name);
            $formInput['image_gallery'] = 'static/dist/img/'.$name;
            }
         }
        //image Gallery

        if($request->status == "preorder") {
            $formInput['date_arrival'] = $request->date_arrival;
        }

        $formInput['user_id'] = Auth::user()->id;
        $new_product = Product::create($formInput);
        if($new_product) {
            Alert::success('', 'Product Berhasil di Tambahkan');
            return redirect('admin/product');
        }
    }


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

Relationship eloquent in laravel?

In user :

    public function posts()
    {
        return $this->hasMany(Post::class);
    }

In post

    public function users()
    {
        return $this->belongsTo(Users::class);
    }

I handle in controller :

$user = Users::find('1')->posts;

Then I get an array. And the result returned is exactly what I need


But when I query this way, the result is an empty array. What did I do wrong? Because I need to get a lot of data.

In UserController.php

$listUser = Users::with('posts')->select('name', 'title')
            ->where('type', 1)
            ->get(); // It returns posts as an empty array

Please give me any comments. Thanks



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

Api routes not found when hosted laravel application on server

I have created my application using laravel and vue.js and hosted my application on server in subfolder inside public_html, Accessing it using url like this:

https://maindomain.in/projectfolder/public/login

but after login if i click on any link it points back to

https://maindomain.in/dashboard

and i get 404 not found in console for the api routes that are accessed for eg. accessing dashboard

https://maindomain.in/api/backend/get-dashboatd-data

My root htaccess file content is :

<IfModule mod_rewrite.c>
RewriteEngine on
</IfModule>

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Force SSL
    RewriteCond %{HTTPS} !=on
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    # Remove public folder form URL
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

and content of .htaccess file inside public folder is

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Note: Frontend is in Vue.js and backend in laravel.

Any help is highly appreciated



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

jeudi 29 juillet 2021

Create array in laravel passing vuejs?

$arrList = [];
foreach ($product as $val) {
    $arrList[]['name'] = $val->name;
    $arrList[]['quantity'] = $val->quantity;
}

return response()->json($arrList);

I am a PHP newbie, so I'm not sure how to handle this. I want the name and quantity to be in the same array.

To the Vue side get the same result?

(2) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0:
name: iphone
quantity: 100
1:
name: samsung
quantity: 130


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

Convert observer to array in vuejs

I am processing in laravel.

$product = Product::selectRaw('name')->groupBy('name')->get();
return response()->json($product);

Result :

(69) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0: {__ob__: Observer}
1: {__ob__: Observer}
2: {__ob__: Observer}
3: {__ob__: Observer}
4: {__ob__: Observer}
5: {__ob__: Observer}

Now i want it like this:

item: Array(69)
[0 … 69]
0: {…}
1: {…}
2: {…}
3: {…}

Give me an idea..Thanks



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

laravel-snappy library allways generate pdf in letter format

I´m traying to generate pdf in my application web with laravel-snappy, and always generate pdf in format landscape but i´m setting other configuration:

public function handle()
    {
        $pdfName = "precontrato.pdf";
        $path    = 'app/contratos/'.$this->precontrato->serie.'-'.$this->precontrato->contador.'/'.$pdfName;
        $pdfPath  = storage_path($path);

        $pdf = PDF::loadView('pdf.precontrato', ['precontrato' => $this->precontrato])
                            ->setPaper('a4')
                            ->setOrientation('portrait')
                            //->setOption('zoom', 1.2)
                            ->setOption('footer-center', 'EDICIONES GRUPO DELUXE 2013 S.L.U está Inscripta en el Registro Mercantil de Granada al Tomo 1548 Folio 42 Hoja GR46323 Inscrip. 1ª')
                            ->setOption('footer-font-size', 5);

        $pdfCreado = $pdf->save($pdfPath, true);

    }

this is my job i´m need a4 format to my pdf but i don´t know, always this library generated me, my pdf in letter format:

this is my snappy.php

'pdf' => [
        'enabled' => true,
        'binary'  => '"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"',
        'timeout' => false,
        'options' => array(
            'encoding' => 'UTF-8',
            'viewport-size' => '1024x768',
            //'margin-top' => 0,
            //'margin-bottom' => 7,
            //'margin-left' => 20,
            //'margin-right' => 20,
            'footer-right' => "Página [page] de [toPage]",
            'footer-font-size' => 3
        )
    ],

    'image' => [
        'enabled' => true,
        'binary'  => '/usr/local/bin/wkhtmltoimage',
        'timeout' => false,
        'options' => [],
        'env'     => [],
    ],

i don´t know where i can to show to change this...

Thanks for help



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

laravel save() returns error Call to undefined method stdClass::save()

Why does save() returns an error "Call to undefined method stdClass::save()" below :

public function update($category,$route)
{
    $category = DB::table('categories')->where('id', $category)->first();
    $category->field = 'changed';
    $category->save();
    ...

and works fine here :

public function store()
{
    ...
    $category = new Category(request(array_column($table->fields, 'name')));
    $category->save();

What do I miss?



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

Processing code is slow when using group by in laravel?

I am processing in laravel, with product table has 300,000 items. In that table there are many duplicate names, so I used groupBy. But it takes a long time to process. Once I load the page and wait for it to finish processing the data, it also takes about 6 seconds to 7 seconds. Is there any way to optimize it fast,Thanks

$listProduct = Product::all()->groupBy('name'); // It takes about 6 seconds to 7 seconds to process this


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

mercredi 28 juillet 2021

cookie::make does not save the cookie in Laravel 8

Am I missing something? I am pulling my hair to solve this simple use of cookie. My intention is simply to save a variable for each user (I tried session and there were side effect issues). The below code should theorically save the cookie which should be there at the next call of the page, correct? It does not work. What am I missing?

class TestController extends Controller
  {
  public function show($page) {
    echo @Cookie::get('testcookie');
    if (Cookie::get('testcookie')) { echo 'cookie exists<br>'; } 
    else { echo 'cookie does not exist<br>'; }
    $cookie = Cookie::make('testcookie','5', 120);
    echo $cookie;
    return view('tests.'.$page,['page' => $page]);
  } 
}

I have also modified config/session.php as recommended for use on http://localhost. Should I clean/cache... or similar after that. I am using laravel 8 & FF on OSX.

'secure' => env('SESSION_SECURE_COOKIE', false)

Can someone please tell me what I am doing wrong?

If I try the other way with response...

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

public function show($page, Request $request)
{
    echo $request->cookie('name');

    if ($request->cookie('name')) { echo 'cookie exists<br>'; } else { echo 'cookie does not exist<br>'; }

    $response = new Response('Set Cookie');

    $cookie = $response->withCookie(cookie('testcookie','5', 120));

    echo $cookie;

    return view('tests.'.$page,[
        'page' => $page
    ]);
} 

I get an error "Call to undefined method Illuminate\Support\Facades\Response::withCookie() ".

Why is it so complicated and so simple in php?



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

Laravel Mutator to add predefined values into database

I'm new into Laravel and I'm trying to store the user's company id on a column of the products table each time a user creates a new product. The company's id it's retrieved from the user's session. I'm trying it with Laravel's Mutator:

public function setFirstNameAttribute($value) {
        $this->attributes['company_id'] = session()->get('company.id');
    }

But each time I create a new Product the company id stored it's null. Seems like the function it's never executing. Is there any other resource to perform actions like this?



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

When creating the role permission it cannot changing the status how can change status in single

//Blade Page

  @foreach ($permission as $permissions)
    <tr>
    <td class="text-center"></td>
     <td></td>
    @foreach ($role as $roles)
    <td class="text-center">
    @if ($roles->name == 'admin'||   $roles->name == 'superadmin')
      <span class="feather feather-check text-success icon-style-circle bg-success-transparent"></span>
    @else
     @csrf
    <input type="hidden"  name="name" class="role" value="">
    <input type="hidden"  name="role_id" class="role_id" value="">
    <input type="hidden" class="permissionid" name="permission[]" value="">
    @foreach ($permissionrule as $item)
        @if ($loop->index)
            @if ($item == null)
        <a href="javascript:void(0)" class="access-icon role1" id="checked1" ><span class="feather feather-x text-danger icon-style-circle bg-danger-transparent"></span>
            @else
        @if ( $item->permission_id ===  $permissions->id &&   $item->role_id === $roles->id)
        <a href="javascript:void(0)" class="access-icon role" id="checked" ><span class="feather feather-check text-success icon-style-circle bg-success-transparent"></span></a>
        @else   
        <a href="javascript:void(0)" class="access-icon role1" id="checked1" ><span class="feather feather-x text-danger icon-style-circle bg-danger-transparent"></span>
        @endif
        @endif  
        @endif
      @endforeach
      @endif
    </td>
    @endforeach
    </tr>
    @endforeach

enter image description here // controller page view part

   public function rolesss(){

        $role = Role::get();
        $data['role'] = $role;

        $permission = Permission::get();
        $data['permission'] = $permission;

        
        $permissionrule = DB::table('role_has_permissions')->get();
        $data['permissionrule'] = $permissionrule;

        return view('admin.roles.index')->with($data);
        
        }

When I creating the role permission and giving to access to the role. Is not changing the status. How can I change the status? Please check the image to tell me anybody know the information about roles and permission.



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

how to use config data in seeder

The use statement with non-compound name 'Config' has no effect. My code constants file:

return [
        'sale_type' => '1',
        'payment' => '2',
        'bill_type' => '3',
        'tax_fixation' => '4',
    ]

Seeder File:

$sale_type =[
            ['text' => 'Order Delivery Sale', 'type_id' => Config::get('sales.sale_type')],
            ['text' => 'Direct Sale', 'type_id' => Config::get('sales.sale_type')], 
            ['text' => 'Advance Sale','type_id' => Config::get('sales.sale_type')],
            ['text' => 'Promotional Sale', 'type_id' => Config::get('sales.sale_type')],
            ['text' => 'Online Sale', 'type_id' => Config::get('sales.sale_type')]
        ];
        DB::table('list_type_selection')->insert( 
            $sale_type
);
    


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

Alternative way for asform() in laravel for authentication?

To call http post request for generating access token in laravel.

$test= Http::withHeaders($headers)->post($url,$parameters);

It throws error like

Unsupported grant type ,grant type is null

When I tried this

$test= Http::withHeaders($headers)->asForm()->post($url,$parameters);

It works fine. But I need to do it with the first code because I used this code every where for API call.so that I can optimize the program.



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

mardi 27 juillet 2021

Compare a string password with laravel Encrypted Password?

I have a laravel website that hashes password on registeration.

I then created simple android application where you can login to the website.

I figured out that I can't login because both passwords are different. The one on the database is hashed while the posted is not!

So I thought of hashing the password before comparing it to database and it was such a stupid idea.

I tried to compare the string to the stored hashed password, here is my login.php:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
 
 
 
 $email = $_POST["email"];
 $password = $_POST["password"];
 $token = $_POST["token"];
 
 $hashedPassword = User::find(1)->password;

if (Hash::check($password, $hashedPassword)) {
    return $hashedPassword;
}
 
    $con=mysqli_connect("localhost", "XXXX", "XXXX", "u787462475_secreta");
    
 

    
 $sql = "SELECT * FROM users WHERE email = '$email' AND password = '$hashedPassword'";
 $result = mysqli_query($con, $sql);
 if($result){
     if (mysqli_num_rows($result)>= 1 ) {
         $json_array['user_details'] = array();
            while($row = mysqli_fetch_assoc($result)){
                $json_array['user_details'][] = $row;
            }

         if($response = array("success" => "1", "user_details" => $json_array, "message"=>"You have been logged in successfully")){


             
         }


     }else{
         $response = array("success" => "0", "message"=>"Please enter valid email and password");
     }
 }else{
      $response = array("success" => "0", "message"=>"Server error");
 }
 
 header('Content-type: application/json');
 echo json_encode($response);
 ?>

I included needed blades such as controller,hash, and request. I then returned $hashedPassword and put it in the sql statement like this: password = '$hashedPassword'

still can't login unless provide the hashed password itself!!

PS: the login.php file that connects android app with database is located at public_html and I made sure blades USE directory are correct.



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

yajra datatable search with space problem

function displayAuditTable(data=[]) {

var  columns = [{data: 'date', name: 'Date',width:"20%"},
    {data: 'user', name: 'User',orderable : false,width:"20%"},
    {data: 'engagement_profile', name: 'Engagement Profile', orderable : false,width:"20%"},
    {data: 'event', name: 'Event', orderable : false,width:"10%"},
    {data: 'description',processing: false,
        serverside: false, "Smart": false, "Regex": true,"Search": " ", orderable: true,width:"30%", searchable: true , name: 'description'}];
data.order = [];
data.sort = ['date','desc'];
$('#audit_trail_table').DataTable().destroy();
initializeDatatable('audit_trail_table', base_url + '/datatables/audit-trail',
    columns, data, 'Audit Trail');

}

This is js when i search user than give me result but when i search user exp than give me not result, i am using yajra datatable



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

how to hide Sidebar menu from users using laravel constant?

I want to hide a sidebar menu from specific user . And I need to implement this using constant.php 'SHOW_FEATURE' => false .



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

Data getting saved as null string in db

I am passing data from vue.js

formData.append('remark', this.form.remark);

 <textarea v-model="form.remark" class="form-control"> </textarea>

  mounted(){ 
                  
          const header = {
            'Authorization' : 'Bearer ' + this.getLoginUserData,
          }
         this.editId = this.$route.params.id;
         axios.get(`/api/backend/userdata/${this.editId}` , {headers : header})
         .then((response) => {   
            this.form = response.data;

form initialization :

form: {
                name: '',
                remark: '',

In my controller i'm getting null string and it is getting saved in database column. so i have to check it manually in my laravel controller to check for null string and if that string is saved in my database then it reflect in textfield also.

if($request->remark == "null")
      {
        $save->remark = "";
      }

But i don't want to check it manually everytime for null string. Any solution will be highly appreciated.



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

lundi 26 juillet 2021

how to setup ckfinder to display image folder after installing in laravel?

I have downloaded and installed the CKfinder 3.5.1.2 laravel package. I have also created a custom build for my CKeditor. So far so good.

Here is my test page.

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>CKEditor 5 ClassicEditor build + CKfinder</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
@include('ckfinder::setup')
<div>
<textarea class="textarea " id="editor">
<h2>Hello</h2>
</textarea>
</div>
<script src="/public/ckeditor/ckeditor.js"></script>
<script src="/public/ckeditor/ckfinder.js"></script>
<script>CKFinder.config( { connectorPath: '/public/ckfinder/connector' } );</script>
<script type="text/javascript">
ClassicEditor
    .create( document.querySelector( '#editor' ), {     
        ckfinder: {
            uploadUrl: '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files&responseType=json'
        },
        toolbar: {
            items: [
                'sourceEditing','heading','bold','italic','subscript','superscript','specialCharacters','|',
                'fontFamily','fontSize','fontColor','fontBackgroundColor','|',
                'alignment','indent','outdent','numberedList','bulletedList','|',
                'link','insertTable','|',
                'imageUpload','imageInsert','CKFinder','mediaEmbed','|',
                'findAndReplace','highlight','removeFormat','undo','redo'
            ]
        },
        language: 'en-gb',
        image: {
            toolbar: [
                'imageTextAlternative','imageStyle:inline','imageStyle:block','imageStyle:side'
            ]
        },
        table: {
            contentToolbar: [
                'tableColumn','tableRow','mergeTableCells','tableCellProperties','tableProperties'
            ]
        },
        licenseKey: '',     
    } )
    .then( editor => {
        window.editor = editor;
    } )
    .catch( error => {
        console.error( error );
    } )
    ;
</script>
</body>
</html>

The problem is that when I click on the CKfinder icon, the popup window displays my home page without any css.

1/ I have not found a clear explanation on how to setup the uploadUrl for CKfinder so I left it as provided in the sample. I guess that this url should point to the location of the connector.php file? Where should the file be placed?

2/ In the vendor/ckfinder-laravel-package, the routes.php contains the following routes:

Route::any('/ckfinder/connector', '\CKSource\CKFinderBridge\Controller\CKFinderController@requestAction')
    ->name('ckfinder_connector');

Route::any('/ckfinder/browser', '\CKSource\CKFinderBridge\Controller\CKFinderController@browserAction')
    ->name('ckfinder_browser');

Route::any('/ckfinder/examples/{example?}', '\CKSource\CKFinderBridge\Controller\CKFinderController@examplesAction')
    ->name('ckfinder_examples');

Should I copy these routes in my own file and change the "\CKFinderBridge\Controller..." to the correct path?



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

samedi 24 juillet 2021

Laravel 5 DB::statement return SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the

Here is statement:

CREATE TEMPORARY TABLE homestead.temp_table
    AS
    SELECT title,content, feed, link, date, created_at, updated_at FROM homestead.news ORDER BY `date` ASC LIMIT 5;

    TRUNCATE homestead.news;

    INSERT INTO homestead.news (title, content, feed, link, date, created_at, updated_at)
    SELECT title, content, feed, link, date, created_at, updated_at FROM homestead.temp_table;

    DROP TEMPORARY TABLE homestead.temp_table;

Code is working in Mysql Workbench but not inside laravel. Please help, this is my first question on Stackoverflow :)



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

Gif image loads on local host but not on hosted server/live site

I am working on a laravel project. I want to show an animated gif on my webpage. The gif image is displaying fine at localhost but at live site, image is displayed broken. I have tried different gif images but still no success. and strange thing i can load jpg or png image from same folder with live site, but gif image does not work. There is no spelling mistake and gif file is present at server.

<img width="100px" height="100px" src="/storage/images/anim.gif">

information from chrome network tab

In picture above is information from chrome network tab



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

Error when saving json to database mysql?

public function store(Request $request)
{
  $image = ['http://localhost.loca/image/product/01-1627140249.jpg', 'http://localhost.loca/image/product/03-169983334.jpg'];
  $product = new Product();
  $product->image = json_encode($image);
  $product->save();
}

And the results are stored in the database

["http:\/\/localhost.loca\/image\/product\/01-1627140249.jpg","http:\/\/localhost.loca\/image\/product\/03-169983334.jpg"]

There are \ being generated. is there any fix. Thanks.



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

user editor, only edit the first record

I am working in a user editor, I have a problem, just edit the first record.

when I want to edit another different user it sends me data only from the first one

  public function usuarios(Request $request){
    $data = [
        'category_name' => 'apps',
        'page_name' => 'contacts',
        'has_scrollspy' => 0,
        'scrollspy_offset' => '',
    ];
 $usuarios = User::All();

    // $pageName = 'contacts';
    return view('usuarios',compact('usuarios'))->with($data);
}
public function userupdate(Request $request){
 

 foreach($request->service as $key=>$value){

    $nuevoIngreso = User::find($value['id']);
    if($nuevoIngreso){
    $nuevoIngreso->name = $value['name'];
    $nuevoIngreso->email = $value['email'];
    $nuevoIngreso->telefono = $value['telefono'];

    $nuevoIngreso->tipo = $value['tipo'];
    $nuevoIngreso->save();
    }
   }

    // $pageName = 'contacts';
    return redirect('usuarios')->with('mensaje', 'Ficha Actualizada.');
}

Blade.php

    @extends('layouts.app')



@section('content')
<div id="tableCheckbox" class="col-lg-12 col-12 layout-spacing">
                            <div class="statbox widget box box-shadow">
                                <div class="widget-header">
                                    <div class="row">
                                        <div class="col-xl-12 col-md-12 col-sm-12 col-12 mt-3 text-center">
                                            <h2>Usuarios</h2>
                                        </div>                       
                                    </div>
                                    
                                </div>
                                <div class="widget-content widget-content-area">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover table-striped table-checkable table-highlight-head mb-4">
                                            <thead>
                                                <tr>
                                                    <th class="checkbox-column">
                                                        <label class="new-control new-checkbox checkbox-primary" style="height: 18px; margin: 0 auto;">
                                                            <input type="checkbox" class="new-control-input todochkbox" id="todoAll">
                                                            <span class="new-control-indicator"></span>
                                                        </label>
                                                    </th>
                                                    <th class="">Nombre</th>
                                                    <th class="">Email</th>
                                                    <th class="">Telefono</th>
                                                    <th class="text-center">ACCIÓNES</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach($usuarios as $key=>$users)
                                                <tr>
                                                    <td class="checkbox-column">
                                                        <label class="new-control new-checkbox checkbox-primary" style="height: 18px; margin: 0 auto;">
                                                            <input type="checkbox" class="new-control-input todochkbox" id="todo-1">
                                                            <span class="new-control-indicator"></span>
                                                        </label>
                                                    </td>
                                                    <td>
                                                        <p class="mb-0"></p>
                                                    </td>
                                                    <td></td>
                                                    <td></td>

                                                    <td class="text-center">
                                                        <ul class="table-controls">
                                                            <li><a href=""  data-placement="top" title="" data-original-title="Settings" data-toggle="modal" data-target="#registerModal"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-settings text-primary"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg></a> </li>
                                                            <li><a href="javascript:void(0);" data-toggle="tooltip" data-placement="top" title="" data-original-title="Edit"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-edit-2 text-success"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path></svg></a></li>
                                                            <li><a href="javascript:void(0);" data-toggle="tooltip" data-placement="top" title="" data-original-title="Delete"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-trash-2 text-danger"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg></a></li>
                                                        </ul>
                                                    </td>
                                                </tr>
                                                <div class="modal fade register-modal" id="registerModal" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel" aria-hidden="true">
                                      <div class="modal-dialog" role="document">
                                        <div class="modal-content">

                                          <div class="modal-header" id="registerModalLabel">
                                            <h4 class="modal-title">Editar Usuario</h4>
                                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button>
                                          </div>
                                          <div class="modal-body">
                                      
                                            <form id="addContactModalTitle" class="mt-0" method="POST" action="">
                                                    
@csrf
<input class="form-control" type="hidden" value="" name="service[][id]">
                                               <div class="form-group">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-user"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                                                <input type="text" class="form-control mb-2" name="service[][name]" id="exampleInputUsername1" value="">
                                              </div>
                                              <div class="form-group">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-at-sign"><circle cx="12" cy="12" r="4"></circle><path d="M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-3.92 7.94"></path></svg>
                                                <input type="email" class="form-control mb-2" name="service[][email]" id="exampleInputEmail2" value="">
                                              </div>
                                              <div class="form-group">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-lock"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                                                <input type="phone" class="form-control mb-4" name="service[][telefono]" id="exampleInputPassword2" value="">
                                              </div>
                                              <div class="form-group">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-lock"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                                                <input type="phone" class="form-control mb-4" name="service[][tipo]" id="exampleInputPassword2" value="">
                                              </div>
                                              <button type="submit" class="btn btn-primary mt-2 mb-2 btn-block">Actualizar</button>
                                            </form>

                                           

                                          </div>
                                         
                                        </div>
                                      </div>
                                    </div>
                                             @endforeach
                                            </tbody>
                                        </table>
                                    </div>

                                  

                                </div>
                            </div>
                        </div>


      

   @endsection

Routes:

 Route::get('usuarios','HomeController@usuarios');
Route::put('/usuarios', 'HomeController@userupdate' )->name('userupdate');

if necessary I can upload a screenshot of the problem to better understand.

When I click on edit the user ID = 2, or 3 sends me data from the user ID 1 only. in list it prints all the records, but in the form it only prints the first user



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

vendredi 23 juillet 2021

Save an array with laravel?

I have an array. Now I save it to the database:

public function store(Request $request)
{
    $link = ['http://localhost.loca/image/img-1627019138.jpg'];

    $product = new Product();
    $product->link = $link;
    $product->save();
}

And it gives such error:

Array to string conversion

I want to save it to the database in the form:

['http://localhost.loca/image/img-1627019138.jpg']

Because it has a lot of links so it has to be saved as an array in the field.



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

I am trying to store name of ordered meals for each user in order table, I am using Larvel

this is the order table

 $table->string('first_name');
        $table->string('last_name');
        $table->string('phone_number');    
        $table->string('meal_name');
        $table->Integer('quantity');

and this is the meal_user table which contains the order informations before confirming it by the user

  $table->double('quantity');
        $table->text('note')->nullble();
        $table->string('meal_size');
        $table->string('first_name')->nullable();
        $table->string('last_name')->nullable();
        $table->string('phone_number')->nullable(); 
        $table->bigInteger('location_id');
        $table->bigInteger('user_id')->nullable();
        $table->bigInteger('meal_id');

what I am trying to do is when the user confirm his orders it stores in the order table, but for each user has one record with all ordered meal names



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

laravel: how to explain the action "name" at web.php under routes folder

I can not understand how below code works in /var/www/html/routes/web.php

Route::get('/import', 'ImportController@ImportStats')->name('import.stats')->middleware('can:import.stats');

'/import', 'ImportController@ImportStats') this part is easy to understand,

but I do not know what name('import.stats') and ('can:import.stats') are....

thanks



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

Connecting DigitalOcean Managed MongoDB to Laravel (connection error calling ismaster)

I'm attempting to set up Laravel with the Managed MongoDB provided by DigitalOcean, though for some reason the database is not connecting.

I've hit a wall and I think it's something to do with authSource, but can't replicate it via cli otherwise...

.env file

MONGO_DSN="mongodb+srv://username:password@digitaloceanhostname/databasename?authSource=admin"
MONGO_DATABASE="databasename"
MONGO_USER="username"
MONGO_PASSWORD="password"
MONGO_TLS=true 
MONGO_TLS_CERT="./mongo-db-cert.crt"

config/database.php

'connectionmethod' => [
    'driver' => 'mongodb',
    'dsn' => env('MONGO_DSN'),
    'database' => env('MONGO_DATABASE', ''),
    'username' => env('MONGO_USER', ''),
    'password' => env('MONGO_PASSWORD', ''),
    'options'  => [
        'tls' => (bool) env('MONGO_TLS', false),
        'tlsCAFile' => env('MONGO_TLS_CERT', null),
        'authSource' => 'admin',
        'db' => 'admin',
        'database' => 'admin',
    ],
],

The above causes the following error:

ERROR: No suitable servers found (`serverSelectionTryOnce` set): [connection error calling ismaster on 'digitaloceanhostname'
(MongoDB\\Driver\\Exception\\ConnectionTimeoutException(code: 13053): No suitable servers found (`serverSelectionTryOnce` set): [connection error calling ismaster on 'digitaloceanhostname:27017']

However, when using the CLI to call ismaster, it works:

# mongo "mongodb+srv://MONGO_USER:MONGO_PASSWORD@digitaloceanhostname/MONGO_DATABASE?authSource=admin" --eval 'printjson(db.runCommand({"isMaster": 1}))' --ssl --sslCAFile ./mongo-db-cert.crt

Running it without the ?authSource=admin causes an authentication error, which is making me think the connection error from laravel is the same thing.

Environment:

# mongo --version
MongoDB shell version v3.6.8

# apt list --installed | grep php | grep mongo
php7.4-mongodb/focal,now 1.9.0+1.7.5-6+ubuntu20.04.1+deb.sury.org+1 amd64 [installed]

# php artisan --version
Laravel Framework 5.8.38

I'm probably missing something obvious, but after looking at this all day any input is appreciated!



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

jeudi 22 juillet 2021

how to create an API for validating login details and loading user data using ajax

how to create an API for validating login details (login.html) and loading user data (data.html) both file extension is .html how to do that thing using ajax



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

Convert array to controller laravel?

In controller:

public function store(Request $request)
{
  $data = $request->all();
  dd($data);
}

Result : {"name":"Joni","age":"18"}

I want to convert it to an array ? give me ideas.Thanks



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

Save model outside of for-each loop

Assuming the model Order

class Order extends Model
{
    use HasFactory;

    protected $table = 'order';

    protected $primaryKey   = 'id';
    public $incrementing = false;
    protected $keyType = 'string';
    protected $guarded = [];

    public function extra(){
        return $this->hasOne(Extra::class);
    }

    public function products(){
        return $this->hasMany(Product::class);
    }
}

and the Model Extra

class Extra extends Model
{

    use HasFactory;
    protected $table = 'extra';
    protected $guarded = [];

    public function order(){
        $this->belongsTo(Order::class);
    }

}

and the Model product

class Product extends Model
{
    use HasFactory;
    protected $table = 'product';
    protected $guarded = [];
    public function order(){
        return $this->belongsTo(Order::class);
    }
}

Now, from an API i receive data. With these data i want to feed the models and then store the info to DB.

The approach there is atm is

foreach ($list as $item) {

    $order = new Order();
    $order->id = $item['id'];
    $order->title = $item['title'];
    $order->save();

    $extra = new Extra();
    $extra->foo= $item['path']['to']['foo'];
    $extra->bar= $item['path']['to']['bar'];
    $order->extra()->save($extra)
    
    $order->products()->createMany($item['path']['to']['products']);
}

The problem is that this code saves three times for each loop, one for order, one for extra, one for product. I would like to know if there is another way that i can use in order to gather the data inside the for-each and outside of it, to make something like Order::insert($array_of_data);



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

Sending the same kind of Job to the laravel Queue Worker

I am trying to send a job one at a time to the queue worker but Laravel Queue Worker is somehow executing the jobs at the same time. Based on the Laravel Queue documentation; it says the jobs execute asynchronously but in my case, it is not. So, I am not sure what's going wrong.

I also tried Job Chaining but it seems Job Chaining allows only different kinds of jobs.

My job's purpose is the same but for different customers.

I appreciate any sort of help.

I am using Laravel 5.6



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

Error processing image with dropzone in laravel 5.6

I´m trying to upload a file with dropzone and laravel 5.6, but my method returns a 405 (Method Not Allowed) error and I don´t know how I can add a token to process the upload.

This is my code in my blade:

<form action="" enctype="multipart/form-data" class="dropzone" id="fileupload" method="POST">
                                    <div class="col-12 mt-3 text-center">
                                        <span>Arrastre o pulse aquí para subir archivos</span>
                                    </div>
                                    <div class="col-12 text-center mt-4 mb-4">
                                        <i class="fas fa-upload fa-4x"></i>
                                    </div>
                                    <div class="col-12 mt-5 text-center">
                                        <span>El tamaño máximo del archivo debe ser inferior a 6MB</span>
                                    </div>

                                    <div class="fallback">
                                        <input name="file" type="files" multiple accept="image/jpeg, image/png, image/jpg" />
                                    </div>
                                </form>

and this is my js script:

<script>
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
        Dropzone.options.myDropzone = 
        {
            url: "",
            headers: {
                'x-csrf-token': CSRF_TOKEN,
            },
            method: "POST",
            data: {"_token": $("meta[name='csrf-token']").attr("content")},
            autoProcessQueue: true,
            maxFilesize: 6,
            acceptedFiles: ".jpeg, .jpg, .png, .gif",
            addRemoveLinks: true,
            paramName: "attached",
            init: function() {
                dzClosure = this;
                this.on("sending", function(data, xhr, formData) {
                    var token = $("meta[name='csrf-token']").attr("content");
                });

                // for Dropzone to process the queue (instead of default form behavior):
                /*document.getElementById("submit-all").addEventListener("click", function(e) {
                    // Make sure that the form isn't actually being sent.
                    e.preventDefault();
                    e.stopPropagation();
                    dzClosure.processQueue();
                });



                //send all the form data along with the files:
                this.on("sendingmultiple", function(data, xhr, formData) {
                    formData.append("firstname", jQuery("#firstname").val());
                    formData.append("lastname", jQuery("#lastname").val());
                });*/
            },
            success: function(file, response) 
            {
                console.log(response);
            },
            error: function(file, response)
            {
               return false;
            }
        }
    </script>

Thanks for reading, any help would be much appreciated.



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

Laravel set column table as unique

I need to add a column on a table database to mark a product as default. The column value has to be true or null (or maybe false if it's easier that way). It must be just one product marked as default so in case one user selects one product as default the previous default product must be marked as null.

I've been trying with unique value and nullable attributes but it's not doing what I want.

I should do it with an Event? there's no simplier way?



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

Pass image vue to controller laravel?

I am handling vue and laravel image upload. I am passing image from vue to controller via axios

In vuejs :

<b-col md="3">
  <b-form-group>
  <label>ImageLogo:</label>
  <b-form-file
  name="image-logo"
  @change="changeImageLogo"
  />
  </b-form-group>
</b-col>
<b-col md="3">
   <b-form-group>
   <label>Success image:</label>
   <b-form-file
   name="success-image"
   @change="changeSuccessImage"
   />
   </b-form-group>
</b-col>
<b-col md="3">
   <b-form-group>
   <label>Fail image:</label>
   <b-form-file
   name="fail-image"
   @change="changeFailImage"
   />
   </b-form-group>
</b-col>
<b-col md="3">
   <b-form-group>
   <label>Image payment success:</label>
   <b-form-file
   name="image-payment"
   @change="changePaymentSuccess"
   />
   </b-form-group>
</b-col>
<b-row>
 <b-col md="5">
   <b-button variant="primary" block type="submit" @click="submitForm">
      Create
    </b-button>
  </b-col>
</b-row>

data () {
  return: {
    logo:'',
    imageSuccess:'',
    failImage:'',
    successPayment:''
  }
},
methods: {
    changeImageLogo(e) {
      let selectFile = e.target.files[0];
      this.logo = selectFile;
     },
     changeSuccessImage(e) {
      let imgSuccess = e.target.files[0];
      this.imageSuccess = imgSuccess;
     },
     changeFailImage(e) {
      let failImg = e.target.files[0];
      this.failImage = failImg;
     },
     successPayment(e) {
      let sspayment = e.target.files[0];
      this.successPayment = sspayment;
     },
     submitForm() {
       let formData = new FormData();
       formData.append("image-log", this.logo);
       formData.append("success-image", this.imageSuccess);
       formData.append("changeFailImage", this.failImage);
       formData.append("image-paymnet", this.successPayment);
     }
}

I use formData.append to pass the controller, but when there are many input files I have to write many methods. Is there a way to combine methods to get images together. Why do I need to pass up to 10 input files? Please give me ideas.Thank



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

mercredi 21 juillet 2021

Property [fechaviso] does not exist on this collection instance

i am new to laravel, i need help with this error Property [fechaviso] does not exist on this collection instance

public function retiro (Request $request){
    $data = [
        'category_name' => 'datatable',
        'page_name' => 'miscellaneous',
    'has_scrollspy' => 0,
    'scrollspy_offset' => '',

    ];
    $registros = Registro::whereNull('retiro')
    ->whereNull('retiro')
    ->get();
    $hoy = Carbon::now();
    $update = Registro::where('id', $request->id)->first();
    

   //fecha1 = date
   //fecha2 = today

    $fecha1= $registros->fechaviso;
   $fecha2= new DateTime();
  $contadorfecha = $fecha1->diff($fecha2);    

  
    if ($request->isMethod('put')) {
        if ($update->retiro = $request->retiro)
        {
            $update->fecharetiro = Carbon::now();
       }
        $update->save();
        return redirect('retirados');
    }
  
    return view('retiro',compact('registros','update','hoy','contadorfecha'))->with($data);
    
}

i calculating the difference between days

    @foreach($registros as $registro)
                                 
                                  
                                   
                                     
                                            <tr>
                                                <td class="checkbox-column"> 1 </td>
                                                <td></td>
                                                <td></td>
                                                <td></td>
                                                <td><span class="shadow-none badge badge-primary"></span></td>
                                                <td class="text-center">
                                            </td>
                                            </tr>
                                       
                                    
                              
                                        @endforeach

DB > https://i.stack.imgur.com/sCXHi.png

I should be able to calculate the days difference, I tried this query but it did not work: Registro::find($request->id); Help pls



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

Set name when uploading image file with laravel

I'm working on uploading pictures to minio in laravel.

Storage::cloud()->put('image', $request->file, 'public');

Upload was successful, but it is saving random name.. now i want to assign name to it, what should i do.

Random name upload : LD7fBO5seB8KMbYFS8wNafjK73hfA7lyUPAarGme.jpg

Give me ideas.Thanks



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

How to handle image uploading + optimization

I have a feature where a user can create a post and upload up to 10 images. Once these images are uploaded, I want to optimize them before making the post public (i.e. it should remain private until the the job to optimize the images finishes running).

How should I handle this?

My current thinking is:

  • User uploads 10 images and submits the post
  • I insert a new row for each image into the database in a table called temp_post_images
  • The images are stored in a temp folder until they are processed by the job
  • The job gets all rows from temp_post_images for that post, loops through each and optimizes each image
  • Once all images are optimized, it moves the entire temp folder into a permanent folder, and all rows in temp_post_images are moved to the permanent post_images table

However, this seems needlessly complicated and prone to errors.

What would a better solution be here?



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

Laravel collective SSH put method not working

I am trying to upload contents from one server to another using LaravelCollective SSH https://laravelcollective.com/docs/5.5/remote

I have successfully installed the package and added it in the Laravel providers and generated its config file successfully. The config/remote.php looks like:

    'connections' => [
        'remoteDropbox' => [
            'host' => '111.222.33.444:222', //ip and port number
            'username' => 'user',
            'password' => 'abc123',
            'key' => '',
            'keytext' => '',
            'keyphrase' => '',
            'agent' => '',
            'timeout' => 300,
        ],
    ],

Also I can able to connect to remote server and execute some code to list contents from server using SSH::into('remoteDropbox')->run() method.

But I cannot able to put content to remote server. I tried:

SSH::into('remoteDropbox')->put(
    "/var/www/html/local-server/public/toExport/test.zip", //localfile
    "/var/www/html/dropbox/public/inbox" //remote path
);

Could anyone tell me why the content is not uploading to remote server. My Laravel version is 5.5 and Laravelcollective/remote is 5.5



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

how to access an array of images in a laravel colloction

i have uploaded images stored in an array in my MySql database. but I don't know how to access the contents of the array in the laravel collection. all the code I tried are giving me error that the array is a string.

this is the query of the posts from the database below.

public function index()
{
    $posts = Post::orderBy('created_at', 'desc')->paginate(10);
    return view('posts.index')->with('posts', $posts);
}

this is the blade template showing the posts

@if (count($posts) > 0)
        @foreach ($posts as $each_post)
            <div class=" shadow-md bg-white pb-3  rounded-md " >
                <div class="  ">
                        <a href="/posts/"><img src="/storage/images/" class=" w-full  object-fill  rounded-t-md h-44 md:h-48" alt=""></a>
                  
                        
         
                </div>
                <div class="p-2">
                    <h3 class=" text-sm md:text-lg text-gray-800 mb-2">
                        <a href="/posts/"></a>
                    </h3>
                     by </small> --}}
                    @if ($each_post->price > 0)
                        <small class=" text-green-500  text-xs md:text-base">   </small>
                    @else
                    <small class=" text-green-500 text-xs md:text-base"> free  </small>
                        
                    @endif
                    
                </div>
            </div>
    
            
        @endforeach
       
    </div>
        
    @else
        <p>No Posts</p>
    @endif

The $each_post->images is where the problem lies.

a dd($each_post) command displays this

 App\Models\Post {#387 
  #connection: "mysql"
  #table: "posts"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:12 [▼
    "id" => 37
    "title" => "happy salah"
    "slug" => "happy-salah-2"
    "description" => "jkjjcjc"
    "price" => "1,500"
    "venue" => "talba junction"
    "contact_info" => "09023234546"
    "created_at" => "2021-07-20 13:49:30"
    "updated_at" => "2021-07-20 13:49:30"
    "user_id" => 1
    "images" => "["downloadfile-2_1626788970.jpeg","downloadfile_1626788970.jpeg"]"
    "author_id" => null
  ]
  #original: array:12 [▼
    "id" => 37
    "title" => "happy salah"
    "slug" => "happy-salah-2"
    "description" => "jkjjcjc"
    "price" => "1,500"
    "venue" => "talba junction"
    "contact_info" => "09023234546"
    "created_at" => "2021-07-20 13:49:30"
    "updated_at" => "2021-07-20 13:49:30"
    "user_id" => 1
    "images" => "["downloadfile-2_1626788970.jpeg","downloadfile_1626788970.jpeg"]"
    "author_id" => null
  ]
  #changes: []
  #casts: []
  #classCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}

please any suggestion?



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

Call to a member function diff() on null - Count days between dates [closed]

i need to create a counter between dates

Controller:

$registro = Registro::where('fechaviso', $request->id)->first();
    $fechaaviso = $registro->fechaviso;
    $fechahoy = new DateTime();
    $contadorfecha = $fechaaviso->diff($fechahoy);

I need to count the days that pass between the date of the variable: $fechaviso, to today.

error:

Call to a member function diff() on null

help pls



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

pdf laravel 5.6 with barryvdh don´t show in vertical

i´m modifying one application in laravel-5.6 and i have a problem when i created my pdf with barryvdh library.

i need that this pdf show in vertical but only can show so:

enter image description here

enter image description here

i think that his size it´s letter... only i can show in landscape... This error, before it did not happen one day, my application start to generate pdf so...

This is configuration in jobs:

pdf = PDF::loadView('pdf.precontrato', ['precontrato' => $this->precontrato])
                            ->setPaper('A4', 'Portrait')
                            ->setOption('zoom', 1.2)
                            ->setOption('footer-center', 'x')
                            ->setOption('footer-font-size', 5);

i don´t know if i have any problem with cache... but if i change this configuration always i show how in pictures.

this is configuration for config/snappy.php

Thanks for help me and readme.



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

mardi 20 juillet 2021

Laravel Equivalent to JavaScript's ...prev

I'm trying to add an attribute to be passed in data but I would like all other attributes to stay.

$data = $request->all();

Is it possible to do this:

$data =[...data, 'Total'=> $total]

I think that ...data is for javascript. Is there an equivalent in laravel?



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

hide records with controller

How can I hide records from my controller? i need to hide the records if the column 'retiro' is not null.

Controller:

   public function retiro (Request $request){
    $data = [
        'category_name' => 'datatable',
        'page_name' => 'miscellaneous',
    'has_scrollspy' => 0,
    'scrollspy_offset' => '',

    ];
    $records = Registro::where('retiro', '<>', 'on')->get();


    return view('retiro',compact('records'))->with($data);
}

if 'retiro' == 'on' should hide the record

the problem is that when printing the records it does not show anything.

enter image description here help pls



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

quiero ejecutar en mi PC un sistema de laravel 5.5 que esta alojado en vultr con base de datos pgadmin [closed]

Tengo problemas al migrar, ya que yo uso mysql y esto uso pgadmin, no se si habra diferencia



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

query laravel 5.6 whereNull condition, return empty array

I´m traying to create a query with whereNull() condition but, return this result:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
        )

)

in my db table i have data whith empty column data:

i need create my query with DB::table() and my query is:

$result = \DB::table('listado')
                                        ->join('llamada AS ll','ll.id_listado','=','listado.id')
                                        ->join('users AS tele','ll.id_teleoperadora','=','tele.id')
                                        ->join('llamada_estado AS estado','ll.id_estado', '=', 'estado.id')
                                        ->join('cita AS c', 'c.id_llamada', 'll.id')
                                        ->join('cita_estado AS ct', 'c.id_estado', 'ct.id')
                                        ->where('listado.cp', '=', $cp)
                                        ->whereNull('listado.id_teleoperadora')
                                        ->select(
                                            'listado.id as listId','listado.nomape as listNom','listado.direccion as listDirec',
                                            'listado.provincia as listPro', 'listado.ciudad as listCiu', /*'tele.nombre as teleNombre',*/ 'estado.nombre as estaNombre',
                                            'ct.nombre as ctNombre', 'll.created_at as llaCreated'
                                        )
                                        ->get();

in my table listado i have column id_teleoperadora and if one call don´t have operator assign this column it´s null.

And i need fill datatable with operator null...

Thanks for read, and for help me



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

Laravel routing 404 not found

I have an image in my public/assets/img folder and locally it routes as it should using:

 <img src="">

However, when I pushed this to a server. it gives a 404 error not found. Is there anything that I am doing wrong?



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

Laravel: These credentials do not match our records

enter image description here

I don't know why, I tried to change my admin's password from the Cpanel, the password is changed successfully but this problem occurs when I try to hit the new password. I also tried the old password, it doesn't work. Any solutions for this problem?



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

Cannot sava data in database in notification file in Laravel

I'm using Laravel Notification and i want to save data in my database table if i write my insert query then i'm getting following error otherwise Notification are running :

TypeError: Return value of App\User::getLogNameToUse() must be of the type string, null

This is the query

public function toMail($notifiable)
    {   
        $users = User::find($notifiable->id);
        $users->verification_link=$link;  
        $users->save();
        ...
        ...
     }


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

laravel transaction vs database statement

what is the differences of following two:

DB::update(
    'update users set votes = 0 where votes < 0'
);
DB::transaction(function () {
    DB::table('users')->where('votes', '<' , 0)->update(['votes' => 0]);
});

Official Laravel doc says

The update method should be used to update existing records in the database

But transaction seems more handful that can react to exceptions.

So in what scenarios one is better than the other?



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

lundi 19 juillet 2021

Laravel 5.8 blade, getting values from nested objects error

I am getting some weird error while working with blade.

It works just like it should when getting the data inside a dd(), but when calling it without a dd(), an error is thrown telling me that it can't find a field in my object.

In my blade file, this works just fine:


This doesn't:

<img src="" />

The error:

Undefined property: stdClass::$image (View: /home/vagrant/code/xxxxxx/resources/views/resources.blade.php)



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

Seeding a pivot table in heroku results to error

I'm deploying a Laravel 5.2 application with a database in Heroku. I've managed to migrate my tables without errors until it's time to seed the tables. The seeding always resulted in an error which is this:

Seeded: RolesTableSeeder
Seeded: PrivilegesTableSeeder
[2021-07-19 18:40:57] production.ERROR: PDOException: SQLSTATE[42703]: Undefined column: 7 ERROR:  column "id" does not exist
LINE 1: ..." ("role_id", "privilege_id") values ($1, $2) returning "id"
                                                                   ^ in /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:335
Stack trace:
#0 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(335): PDOStatement->execute()
#1 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(722): Illuminate\Database\Connection->Illuminate\Database\{closure}()
#2 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(685): Illuminate\Database\Connection->runQueryCallback()
#3 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(349): Illuminate\Database\Connection->run()
#4 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(312): Illuminate\Database\Connection->select()
#5 /app/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/PostgresProcessor.php(20): Illuminate\Database\Connection->selectFromWriteConnection()
#6 /app/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2107): Illuminate\Database\Query\Processors\PostgresProcessor->processInsertGetId()
#7 [internal function]: Illuminate\Database\Query\Builder->insertGetId()
#8 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(1423): call_user_func_array()
#9 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1628): Illuminate\Database\Eloquent\Builder->__call()
#10 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1597): Illuminate\Database\Eloquent\Model->insertAndSetId()
#11 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1488): Illuminate\Database\Eloquent\Model->performInsert()
#12 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(574): Illuminate\Database\Eloquent\Model->save()
#13 /app/database/seeds/RolePrivilegesTableSeeder.php(33): Illuminate\Database\Eloquent\Model::create()
#14 /app/database/seeds/RolePrivilegesTableSeeder.php(17): RolePrivilegesTableSeeder->addPrivilege()
#15 /app/vendor/laravel/framework/src/Illuminate/Database/Seeder.php(39): RolePrivilegesTableSeeder->run()
#16 /app/database/seeds/DatabaseSeeder.php(17): Illuminate\Database\Seeder->call()
#17 /app/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(63): DatabaseSeeder->run()
#18 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2314): Illuminate\Database\Console\Seeds\SeedCommand->Illuminate\Database\Console\Seeds\{closure}()
#19 /app/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(64): Illuminate\Database\Eloquent\Model::unguarded()
#20 [internal function]: Illuminate\Database\Console\Seeds\SeedCommand->fire()
#21 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(507): call_user_func_array()
#22 /app/vendor/laravel/framework/src/Illuminate/Console/Command.php(169): Illuminate\Container\Container->call()
#23 /app/vendor/symfony/console/Command/Command.php(256): Illuminate\Console\Command->execute()
#24 /app/vendor/laravel/framework/src/Illuminate/Console/Command.php(155): Symfony\Component\Console\Command\Command->run()
#25 /app/vendor/symfony/console/Application.php(794): Illuminate\Console\Command->run()
#26 /app/vendor/symfony/console/Application.php(186): Symfony\Component\Console\Application->doRunCommand()
#27 /app/vendor/symfony/console/Application.php(117): Symfony\Component\Console\Application->doRun()
#28 /app/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(107): Symfony\Component\Console\Application->run()
#29 /app/artisan(35): Illuminate\Foundation\Console\Kernel->handle()
#30 {main}

Next Illuminate\Database\QueryException: SQLSTATE[42703]: Undefined column: 7 ERROR:  column "id" does not exist
LINE 1: ..." ("role_id", "privilege_id") values ($1, $2) returning "id"
                                                                   ^ (SQL: insert into "role_privileges" ("role_id", "privilege_id") values (1, 1) returning "id") in /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:729
Stack trace:
#0 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(685): Illuminate\Database\Connection->runQueryCallback()
#1 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(349): Illuminate\Database\Connection->run()
#2 /app/vendor/laravel/framework/src/Illuminate/Database/Connection.php(312): Illuminate\Database\Connection->select()
#3 /app/vendor/laravel/framework/src/Illuminate/Database/Query/Processors/PostgresProcessor.php(20): Illuminate\Database\Connection->selectFromWriteConnection()
#4 /app/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php(2107): Illuminate\Database\Query\Processors\PostgresProcessor->processInsertGetId()
#5 [internal function]: Illuminate\Database\Query\Builder->insertGetId()
#6 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php(1423): call_user_func_array()
#7 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1628): Illuminate\Database\Eloquent\Builder->__call()
#8 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1597): Illuminate\Database\Eloquent\Model->insertAndSetId()
#9 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(1488): Illuminate\Database\Eloquent\Model->performInsert()
#10 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(574): Illuminate\Database\Eloquent\Model->save()
#11 /app/database/seeds/RolePrivilegesTableSeeder.php(33): Illuminate\Database\Eloquent\Model::create()
#12 /app/database/seeds/RolePrivilegesTableSeeder.php(17): RolePrivilegesTableSeeder->addPrivilege()
#13 /app/vendor/laravel/framework/src/Illuminate/Database/Seeder.php(39): RolePrivilegesTableSeeder->run()
#14 /app/database/seeds/DatabaseSeeder.php(17): Illuminate\Database\Seeder->call()
#15 /app/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(63): DatabaseSeeder->run()
#16 /app/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(2314): Illuminate\Database\Console\Seeds\SeedCommand->Illuminate\Database\Console\Seeds\{closure}()
#17 /app/vendor/laravel/framework/src/Illuminate/Database/Console/Seeds/SeedCommand.php(64): Illuminate\Database\Eloquent\Model::unguarded()
#18 [internal function]: Illuminate\Database\Console\Seeds\SeedCommand->fire()
#19 /app/vendor/laravel/framework/src/Illuminate/Container/Container.php(507): call_user_func_array()
#20 /app/vendor/laravel/framework/src/Illuminate/Console/Command.php(169): Illuminate\Container\Container->call()
#21 /app/vendor/symfony/console/Command/Command.php(256): Illuminate\Console\Command->execute()
#22 /app/vendor/laravel/framework/src/Illuminate/Console/Command.php(155): Symfony\Component\Console\Command\Command->run()
#23 /app/vendor/symfony/console/Application.php(794): Illuminate\Console\Command->run()
#24 /app/vendor/symfony/console/Application.php(186): Symfony\Component\Console\Application->doRunCommand()
#25 /app/vendor/symfony/console/Application.php(117): Symfony\Component\Console\Application->doRun()
#26 /app/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(107): Symfony\Component\Console\Application->run()
#27 /app/artisan(35): Illuminate\Foundation\Console\Kernel->handle()
#28 {main}



  [Illuminate\Database\QueryException]
  SQLSTATE[42703]: Undefined column: 7 ERROR:  column "id" does not exist
  LINE 1: ..." ("role_id", "privilege_id") values ($1, $2) returning "id"
                                                                     ^ (SQL:
  insert into "role_privileges" ("role_id", "privilege_id") values (1, 1) ret
  urning "id")



  [PDOException]
  SQLSTATE[42703]: Undefined column: 7 ERROR:  column "id" does not exist
  LINE 1: ..." ("role_id", "privilege_id") values ($1, $2) returning "id"
                                                                     ^

I've tried setting the $primary_key to null and one of the id columns in the pivot table but it always returns this error.



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

Laravel installer throws error when creating new project

I am currently learning PHP and I have decided to try and learn Laravel. So I am sorry if my problem is easily fixable, I just can't figure it out

So I am trying to create new Laravel application.

I have installed XAMPP and Composer. With Composer ( composer global require laravel/installer ) I have installed Laravel. But when I try to use laravel new firstProject command to create new command the instalation throws two errors.

I am using Windows 10 if that helps.

 [RuntimeException]
  The archive may contain identical file names with different capitalization (which fails on case insensitive filesys
  tems): ZipArchive::extractTo(C:\Users\User1\Desktop\PHP/vendor/composer/374ddf59/laravel-laravel-8e55104\public/rob
  ots.txt): Failed to open stream: Permission denied

  [ErrorException]
  ZipArchive::extractTo(C:\Users\User1\Desktop\PHP/vendor/composer/374ddf59/laravel-laravel-8e55104\public/robots.txt
  ): Failed to open stream: Permission denied

I have tried:

  1. Reinstalling and updating composer
  2. Reinstalling and updating Laravel
  3. Changing folder where I want to create my project
  4. Using the composer create-project laravel/laravel blog command to create new project through composer still the same errors as above


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

Laravel- Check the manual that corresponds to your MariaDB server version for the right syntax to use near ') < Now()' at line 1

I keep getting this error when executing my program with Laravel:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ') < Now()' at line 1 (SQL: select count(*) as aggregate from `house` where `isoccupied` = 0 and (currentdatasync + INTERVAL '1 DAY') < Now())

my function in my controller is:

  public function view()
    {
        $failed = DB::table('house')
            ->where('isoccupied', 0)
            ->whereRaw("(currentdatasync + INTERVAL '1 DAY') < Now()")
            ->count('*');

        return view('admin.dashboard')->with('failed', $failed);
    }

I have tried to use

return view('admin.dashboard')->with(compact($failed));

however it still does not work.

Has anyone experienced this before?



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

Can you show database records on a View with no Controller in Laravel?

I am new to Laravel and I tried to create an application for an admin. I did other pages first where I ran queries to pull data from the database and display in tables. I made use of an admin middleware for security and if the user in an admin, they get taken to my Dashboard screen(which I left blank till now). Now I want to add items to that Dashboard page and some database records would need to be on it but I see that I have no controller for my Dashboard page. Is there any way to work around this so that I can run these queries?



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

dimanche 18 juillet 2021

Pass my valuess from php to html in laravel [closed]

This is the output of SQL Query. I am using Laravel. I want to pass these values to chart i dont know how. I am new to this can any one help me.

[{"num":"2021-06-24","createdcount":1},{"num":"2021-07-02","createdcount":3},{"num":"2021-07-05","createdcount":1},{"num":"2021-07-06","createdcount":1},{"num":"2021-07-07","createdcount":2},{"num":"2021-07-08","createdcount":2},{"num":"2021-07-09","createdcount":2},{"num":"2021-07-10","createdcount":3},{"num":"2021-07-11","createdcount":2},{"num":"2021-07-12","createdcount":1},{"num":"2021-07-13","createdcount":2},{"num":"2021-07-14","createdcount":2},{"num":"2021-07-15","createdcount":2},{"num":"2021-07-16","createdcount":1},{"num":"2021-07-18","createdcount":1}]

But i want in this format

[{num:"2021-06-24","createdcount":1},{num:"2021-07-02","createdcount":3},{num:"2021-07-05","createdcount":1},{num:"2021-07-06","createdcount":1},{num:"2021-07-07","createdcount":2},{num:"2021-07-08","createdcount":2},{num:"2021-07-09","createdcount":2},{num:"2021-07-10","createdcount":3},{num:"2021-07-11","createdcount":2},{num:"2021-07-12","createdcount":1},{num:"2021-07-13","createdcount":2},{num:"2021-07-14","createdcount":2},{num:"2021-07-15","createdcount":2},{num:"2021-07-16","createdcount":1},{num:"2021-07-18","createdcount":1}]

can any one help me?



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

Parse Json content in model in Laravel

I have a payment and Payment history models

Payment History:

class PaymentHistory extends Model
{
    public function subscription()
    {
        return $this->hasOne('App\Models\Payment', 'id','payment_id');
    }

}

Payment :

class Payment extends Model
    {
        public function PaymentHistory(){
        return $this->belongsTo('App\Models\PaymentHistory ','id','payment_id');
    }
    
    }

I have a json column named as response in Payment History table that i want to return it after decoding json data in model function with each and every row

My query in controller is as follows

 $data = User::with('Payment.PaymentHistory')->get();

i was trying to do something like this in payment history model:

   public function json_response() 
    {
        return json_decode($json, TRUE);
    }

Any help is highly appreciated



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