dimanche 30 juin 2019

Creating a default object from empty value while updating user profile record

I want to update user profile record, but while submitting, an error popped up with a message "Creating default object from empty value", when i remove if statements,and type only var_dump($data),,, it is running smoothly, and show all data, but in the presence of if commands, error popped up. i don't know, why it's happening, any help please,

class home extends Model {

protected $table="homes";
public static function upstore($data){
$firstname=Input::get('fname');
$lastname=Input::get('lname');
$phone=Input::get('phone');
$address=Input::get('address');
$profileimage=Input::get('pimage');
$password=Input::get('pswrd');
$confirmpassword=Input::get('cpswrd');

  if( $firstname != '' ){
    $homes->fname    = $firstname;
  }
 if( $lastname != '' ){
    $homes->lname    = $lastname;
  }
 if( $phone != '' ){
    $homes->phone    = $phone;
  }
 if( $address != '' ){
    $homes->address    = $address;
  }
 if( $profileimage != '' ){
    $homes->pimage    = $profileimage;
  }
 if( $password != '' ){
    $homes->pswrd    = $password;
  }
 if( $confirmpassword != '' ){
    $homes->cpswrd    = $confirmpassword;
  }

     $homes->save();
 }

}

It shows this error "Creating a default object from empty value"



via Chebli Mohamed

jeudi 27 juin 2019

Have another form and want to post for category in website

I have two form, In first form I have content, info, title, pic and columns category AND in another form I have name, category column.

First form of data is showing in website under menu and sub-menu.

Now I want to show the data of another form in sub-menu with id=13, and here is table image

post table https://ibb.co/s3bLMdg another table https://ibb.co/gPZ73Zz.

my view is for 2nd form like where i am storing the value of my id 13

        <div class="form-group table-dark text-white">
                                                               <input type="hidden" id="category" name="category_id" value="13">
                                                        </div>

but, still it' not showing on website



via Chebli Mohamed

Laravel 5.1 unexpected logout after redirect during login

I am working a personal project in Laravel 5.1 For some weird reason, I am not able to login.

When I submit the login form, no exception is thrown. I am automatically redirected to the home page and I am not logged in.

I have tried following remedies without any success as mentioned in here Laravel automatically logged out after few seconds?

  1. I have changed SESSION_DRIVER to database from file.
  2. I have changed the cookie value in config/session.php
  3. I have cleared the cashed and ran compose dump-autoload

I still have no success.



via Chebli Mohamed

How to fix: Duplicating path when using fopen on Laravel?

I'm using laravel 5.1, i'm trying to send a file that my Laravel application creates to an api, in a http request, the file was created in the right place on my application, but when i try to read this with fopen to append on the body of request, it gives the follow error:

fopen(/home/user/code/folder/application/storage//home/user/code/folder/application/storage/pdf/group/38/file.pdf): failed to open stream: No such file or directory {"exception":"[object] (ErrorException(code: 0):

I tried to use a laravel feature called "Storage" (https://laravel.com/docs/5.1/filesystem), but when i use that, i have unknown errors to send by a GuzzleHttpRequest, then it works when i using an existing path with fopen

The code that get the file to send is:

fopen(storage_path("{$doc->filepath}/{$doc->id}/{$doc->name}"), 'r');

It working when was like that:

fopen("../{$doc->filepath}/{$doc->id}/{$doc->name}"), 'r');

The path that i need to get is "/home/user/code/folder/application/storage/pdf/group/38/file.pdf"



via Chebli Mohamed

mercredi 26 juin 2019

How to write laravel 5.8 controllers routes similar to laravel 5.1

Having more than 20 controllers. It's very difficult to set each and every routes for add, edit and delete (also having more actions).

This is my laravel 5.1 routes.php :

Route::controllers([
  'user' => 'UserController',
  'taxes' => 'TaxController',
]);

Is there any way to support these routes in laravel 5.8?



via Chebli Mohamed

lundi 24 juin 2019

Laravel Multi-language Route Prefix

I managed to get some routes working with and without a prefix. Having routes that do not have the prefix work properly is important as it's too much work to go back and change all get/post links to the correct localized ones.

For example with the code below the url localhost/blog redirects to localhost/en/blog (or any other language stored in session).

However, I noticed that URLs with parameters dont work, so /blog/read/article-name will result in a 404 instead of redirecting to /en/blog/read/article-name.

Routes:

Route::group([
  'prefix' => '{locale}',
  'middleware' => 'locale'],
  function() {
  Route::get('blog', 'BlogController@index');
  Route::get('blog/read/{article_permalink}', 'BlogController@view');
  });

Middleware responsible for the redirects which doesnt seem to fire at all for some routes, as if the route group isn't matching the url.

    public function handle($request, Closure $next)
    {
      if ($request->method() === 'GET') {
          $segment = $request->segment(1);

          if (!in_array($segment, config('app.locales'))) {
              $segments = $request->segments();
              $fallback = session('locale') ?: config('app.fallback_locale');
              $segments = array_prepend($segments, $fallback);

              return redirect()->to(implode('/', $segments));
          }

          session(['locale' => $segment]);
          app()->setLocale($segment);
      }

      return $next($request);
    }



via Chebli Mohamed

mercredi 19 juin 2019

vendredi 14 juin 2019

Laravel custom validation to all model

I am using laravel latest version and i have a common field in all model called slug.I would to check whether slug is unique or not. i have slug field in all tables

so i have extended Valdiator class

class CustomValidator extends Validator{

protected function validateIsUniqueSlug($attribute, $value, $parameters)
    {

        $isSlugExist= User::where('slug', $value)->exists();
        if ($isSlugExist) {
            return false;
        }
        return true;
    }

}

this works but problem here is i need to repeat this for models but i dont want to do this .is there any better approach so i can handle it in one method

i know laravel has sluggable package but for some reason i cant use that package



via Chebli Mohamed

mercredi 12 juin 2019

How to display multiple post in single blade by using two row(example starting post, expired_date post)

I have a category page and in this I want to display two types of box in single page, one is starting_post and old_post or expired, how can divide a single page in two part?

class FrontendController extends Controller { public function welcome()

{

    // @TODO Refactor This Line
    return view('welcome')

        ->with('title', Setting::first()->site_name)
        ->with('levels', Category::take(7)->get())

        ->with('levels', Category::take(7)->get())
        ->with('first_post', Post::orderBy('created_at','asc')->first())
        ->with('second_post', Post::orderBy('created_at', 'asc')->skip(1)->take(1)->get()->first())
        ->with('third_post', Post::orderBy('created_at','asc')->skip(2)->take(2)->get()->first())
        ->with('forth_post', Post::orderBy('created_at','asc')->skip(3)->take(3)->get()->first())
        ->with('HOME', Category::find(1))
        ->with('ABOUT US', Category::find(2))
        ->with('RESEARCH', Category::find(3))
        ->with('NEWS AND PUBLICATION', Category::find(4))
        ->with('EVENTS', Category::find(5))
        ->with('PEOPLE', Category::find(6))
        ->with('CONTACT US',Category::find(7));

}



public function singlePost($slug)

{
    $post=Post::whereSlug($slug)->first();

    return view('single')->with('post', $post)

                                ->with('content', $post)

                               ->with('levels', Category::take(7)->get());

}

public function category($slug)

{ $category=Category::whereSlug($slug)->firstOrFail();

   return view($category->getTemplateFile())->with('category', $category)

                                 ->with('title',$category->name)

                                 ->with('levels', Category::take(7)->get());

}

public function events($slug) { $post = Post::where('slug', $slug)->first();

   $coming_events = Post::where('id', '>', $post->id)->desc('id');
   $past_events = Post::where('id', '<', $post->id)->asc('id');

   return view('events_blade')

       ->with('post', $post)
           ->with('categories', Category::take(7)->get())
           ->with('next', Post::find($coming_events))
           ->with('prev', Post::find($past_events));

}

}



via Chebli Mohamed

mardi 11 juin 2019

no error, but data not shown, stuck in processing

enter image description here These are my files which is not showing my data in html only data is processing and no error also. I want to look my database through laravel in a html file but it's only processing and also not showing any error. so please help me on this error.

  • no error, the ajax response is good, but data not shown and processing box keeps showing.

  • Yajra 9.0

  • Laravel 5.8

MemberController.php

<?php

namespace App\Http\Controllers;
use App\Models\Member;
use Illuminate\Http\Request;
use Datatables;
use Validator;

class MemberController extends Controller
{
public function addSocialMember(){
  return view("home.views.social-member");
}

public function listMember(){
  return view("home.views.memberlist");
}

public function listAllMember(){
  $memberlist = Member::query();
  return Datatables::of($memberlist)->make(true);
}

public function saveMember(Request $request){
    $validator = Validator::make(array(
      "name"=>$request->name,
      "email"=>$request->email,
      "phone"=>$request->phone,
      "state"=>$request->state,
      "city"=>$request->city,
      "issue"=>$request->issue,
      "message"=>$request->message,
    ),array(
      "name"=>"required",
      "email"=>"required|unique:member",
      "phone"=>"required",
      "state"=>"required",
      "city"=>"required",
      "issue"=>"required",
      "message"=>"required",
    ));

    if($validator->fails()){

      return redirect("social-member")->withErrors($validator)->withInput();
    }else{

      //successfully we have passed our form
      $member = new Member;
      $member->name = $request->name;
      $member->email = $request->email;
      $member->phone = $request->phone;
      $member->state = $request->state;
      $member->city = $request->city;
      $member->issue = $request->issue;
      $member->message = $request->message;

      $member->save();

      $request->session()->flash("message","Member has been submitted form successfully");

      return redirect("social-member");
    }
}

}

Memberlist.blade.php

@extends("home.layouts.layout")

@section("title","Social Member | Bheekho Foundation")

@section("content")
<div class="container padding-top-three">
<br/>
  <blockquote><h4>We need  Help</h4></blockquote>
<br/>
<div class="row">
    <div class="col-md-12">
        <table class="table table-striped table-bordered" id="memberlist">
          <thead>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>State</th>
            <th>City</th>
            <th>Issue</th>
            <th>Describe Your Issues</th>
                  <th>Status</th>
          </thead>
        </table>
    </div>
  </div>

@endsection


web.php

<?php

Route::get("/","HomeController@homepage");

 //Social Member Route
Route::get("/social-member","MemberController@addSocialMember")->name("addsocialmember");


Route::get("/memberlist","MemberController@listMember")->name("listmember");


Route::get("/memberlist-data","MemberController@listAllMember")->name("listallmember");


Route::post("/save-member","MemberController@saveMember")->name("savemember");



via Chebli Mohamed

lundi 10 juin 2019

I have uploaded a pdf file and it's not showing on website when click on pdf link

I have uploaded the pdf link on website and when clicked on link it's not showing pdf file.

view

<div class="entry-content">

   <a  target="_blank" href=""><p style="font- 
      size: 
      18px;color: #468b10;">   </p>
   </a>

</div>

controller

      public function show($id)

    {

        $file=Post::find($id);

        $content = base64_decode($file->content);

        return response($content)->header('Content-Type', $file->file);
}

public function store(Request $request) {

if (request('file'))

{

        $file = request('file');

        $file_name = time() . $file->getClientOriginalName();

        $file->move('uploads/posts', $file_name);

        $data['file'] = 'uploads/posts/'.$file_name;

    }

}



via Chebli Mohamed

how to redirect and show error validateion in laravel

good day, I new in laravel Framework and I face this two problems : -
first one
I want to redirect to my page after 2 seconds automatically.
the second one
I make custom function call (is exist ) if this function returns true data I want to print "name exist before " but the problem here is form was rested when this function returns true and print message. how to prevent form resetting from inputs value? here is my code

controller code

enter code here
public function add(Request $request)

{
        // start add
    if($request->isMethod('post'))
    {
        if(isset($_POST['add']))
        {
            // start validatio array
        $validationarray=$this->validate($request,[
            //'name'  =>'required|max:25|min:1|unique:mysql2.products,name|alpha',
            'name'  =>'required|alpha',
            'price' =>'required|numeric',

            ]);
                // check name is exist

            if(true !=dBHelper::isExist('mysql2','products','`status`=? AND `deleted` =? AND `name`=?',array(1,1,$validationarray['name'])))
            {

                $product=new productModel();
                // start add
                $product->name=$request->input('name');
                $product->save();
                $add=$product->id;
                $poducten=new productEnModel();
                $poducten->id_product=$add;
                $poducten->name=$request->input('name');
                $poducten->price=$request->input('price');
                $poducten->save();
                $dataview['message']='data addes';




            }else{
                $dataview['message']='name is exist before';
            }

        }
    }
    $dataview['pagetitle']="add product geka";
    return view('productss.add',$dataview);
}

this is my routes

Route::get('/products/add',"produtController@add");
    Route::post('/products/add',"produtController@add");

this is my view

@extends('layout.header')
@section('content')
    @if(isset($message))
        
    @endif

    @if(count($errors)>0)
        <div class="alert alert-danger">
            <ul>
              @foreach($errors->all() as $error)
                  <li></li>

                  @endforeach

            </ul>

        </div>
        @endif

    <form role="form"  action="add" method="post" enctype="multipart/form-data">
        
        <div class="box-body">
            <div class="form-group">
                <label for="exampleInputEmail1">Employee Name</label>
                <input type="text" name="name" value="" class="form-control" id="" placeholder="Enter Employee Name">
            </div>

            <div class="form-group">
                <label for="exampleInputEmail1">Email Address</label>
                <input type="text" name="price" value="" class="form-control" id="" placeholder="Enter Employee Email Address">
            </div>
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
            <button type="submit" name="add" class="btn btn-primary">Add</button>
        </div>
    </form>

@endsection



via Chebli Mohamed

dimanche 9 juin 2019

Error in redirect to previous page after successful register in Laravel?

I get this error "Header may not contain more than a single header, new line detected" when trying to redirect the user to the same page after successful registered. I can't see what I'm doing wrong

Here is the code in register controller

 public function showRegistrationForm()
 {
    if (session('link')) {
        $myPath     = session('link');
        $registerPath  = url('/register');
        $previous   = url()->previous();
        if ($previous = $registerPath)
        {
            session(['link' => $myPath]);
        }
        else
        {
            session(['link' => $previous]);
        }
    }
     else
     {
        session(['link' => url()->previous()]);
    }
    return view('auth.register');
  }

  protected function redirectTo()
  {
    return redirect(session('link'));
  }



via Chebli Mohamed

mercredi 5 juin 2019

How to post data in sub-category in website

I have made category table and created subcategory with the help of parent_id, and now I want to post data in subcategory in website, as I am able to post the data for category but not idea how to to do that for subcategory.

Create.blade.php

            @extends ('layouts.app')

@section('content')

<!-- End Sidebar scroll-->
</aside>
<!-- ============================================================== -->
<!-- End Left Sidebar - style you can find in sidebar.scss  -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Page wrapper  -->
<!-- ============================================================== -->
<div class="page-wrapper">
    <!-- ============================================================== -->
    <!-- Container fluid  -->
    <!-- ============================================================== -->
    <div class="container-fluid">
        <!-- ============================================================== -->
        <!-- Bread crumb and right sidebar toggle -->
        <!-- ============================================================== -->

        <!-- ============================================================== -->
        <!-- End Bread crumb and right sidebar toggle -->
        <!-- ============================================================== -->
        <!-- ============================================================== -->
        <!-- Start Page Content -->
        <!-- ============================================================== -->
        <!-- Row -->
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header bg-info">
                        <div class="text-center">

                        </div>

                        @if(count($errors)>0)
                            <ul class="list-group">
                                @foreach($errors->all() as $error)
                                    <li class="list-group-item text-danger">
                                        
                                    </li>
                                @endforeach
                            </ul>
                        @endif

                            <div class="panel-heading">

                                <div class="text-center text-white">
                                    <b> <h2>Create a new Blog</h2></b>
                                </div>
                            </div><BR>
                            <div class="panel-body">
                                <form action="" method="post" enctype="multipart/form-data">
                                    


                                    <div class="form-group table-dark text-white">
                                        <label for ="category"><h3>Select a Menu</h3></label>
                                        <select name="category_id" id="category" class="form-control" >
                                            @foreach($levels as $category)
                                                <option value=""></option>
                                            @endforeach
                                        </select>
                                    </div>





                                    <div class="form-group text-white">
                                        <label for ="title"><h3>Option1 date/Name Manually</h3></label>
                                        <input type="text" name="opt_1" class="form-control text-danger">
                                    </div>

                                    <div class="form-group text-white">
                                        <label for ="title"><h3>Option2 date/Name Manually</h3></label>
                                        <input type="text" name="opt_2" class="form-control text-danger">
                                    </div>

                                    <div class="form-group text-white">
                                        <label for ="title"><h3>Title</h3></label>
                                        <input type="text" name="title" class="form-control text-danger">
                                    </div>


                                    <div class="form-group text-white">
                                        <label for ="featured"><h3>Image/Featured</h3></label> <input type="file" name="featured" class="form-control">
                                    </div>

                                    <div class="form-group text_white">

                                        <label for ="file"><h3>PDF file</h3></label><input type="file" name="file" class="form-control">
                                    </div>




                                    <div class="form-group text-white" >
                                        <label for ="content"><h3>Content</h3></label>
                                        <textarea name="content" id="content" cols="5" rows="5" class="form-control"> </textarea>
                                    </div>

                                    <div class="form-group">
                                        <div class="text-center">
                                            <button class="btn btn-success" type="submit"> Submit Blog</button>
                                        </div>
                                   </div>
                                </form>
                            </div>
                    </div>


                        </div>
                        @stop

                        @section('styles')

                            <link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.css" rel="stylesheet">

                        @stop

                        @section('scripts')

                            <script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.11/summernote.js"></script>


                            <script>
                                $(document).ready(function() {
                                    $('#content').summernote();
                                });

                            </script>
                        <!-- Row -->

                    javascript:
                    -------------
                    <script type="text/javascript">
                        $.ajaxSetup({
                            headers: {
                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                            }
                        });

                        $(document).ready(function(){
                            $('#name').on('change',function(e){
                                console.log(e);
                                var parent_id= e.target.value;
                                $.getJSON('/your url/sub?parentID=' + parent_id, function(data){

                                    console.log(data);
                                    $('#sub_cat_id').empty();
                                    $.each(data,function(index, sub_cat_id){
                                        $('#sub_cat_id').append('<option value="'+sub_cat_id.id+'">'+sub_cat_id.name+'</option>');
                                    });
                                });

                            });
                        });
                    </script>


                    </div>
                </div>
            </div>
        </div>
        <!-- Row -->

@stop

FrontendController

              public function welcome()

{

    // @TODO Refactor This Line
    return view('welcome')

        ->with('title', Setting::first()->site_name)
        ->with('levels', Category::take(7)->get())
        ->with('first_post', Post::orderBy('created_at','desc')->first())
        ->with('second_post', Post::orderBy('created_at', 'desc')->skip(1)->take(1)->get()->first())
        ->with('third_post', Post::orderBy('created_at','desc')->skip(2)->take(2)->get()->first())
        ->with('forth_post', Post::orderBy('created_at','desc')->skip(3)->take(3)->get()->first())
        ->with('HOME', Category::find(1))
        ->with('ABOUT US', Category::find(2))
        ->with('RESEARCH', Category::find(3))
        ->with('NEWS AND PUBLICATION', Category::find(4))
        ->with('EVENTS', Category::find(5))
        ->with('PEOPLE', Category::find(6))
        ->with('CONTACT US',Category::find(7));

}

PostController.

            public function store(Request $request)
{
    $this->validate($request, [


        'title' =>'required',
        'opt_1'=>'required',
        'opt_2'=>'required',
        'featured'=>'mimes:jpeg,pdf,docx,png:5000',
        'file'=>'mimes:jpeg,pdf,docx,png:5000',
        'content'=>'required',
        'category_id'=>'required',


    ]);

    // Create Initial Required Data ARray
    $data = [

        'opt_1'=>$request->opt_1,
        'opt_2'=>$request->opt_2,
        'title'=>$request->title,
        'content'=>$request->content,
        'category_id'=>$request->category_id,


        'slug'=>str_slug($request->title)
    ];

    if(request('opt_1'))
    {
        $opt_1=request('opt_1');

    }




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

    // Optionally add 'file' if found to the Data array
    if (request('file')) {
        $file = request('file');
        $file_name = time() . $file->getClientOriginalName();
        $file->move('uploads/posts', $file_name);

// $content = base64_encode(file_get_contents($_FILES['pdf'['tmp_name']));

        $data['file'] = 'uploads/posts/'.$file_name;


        //$data->content=$content;
    }



    // Create the Post with the $data Array




    $post = Post::create($data);


    Session::flash('success', 'New Blog has been Published on Website for Particular Menu');

    return redirect()->back();

}



via Chebli Mohamed

lundi 3 juin 2019

Hod do i make discount percentage of products in Laravel

I want to show a discount percentage of my products.

I get this error:

Division by zero (0)

Can anyone suggest me that what's I'm doing wrong ?

@foreach ($Products as $product)
            <div>
                <span>% <br />OFF</span>
                <img src="" />
            </div>
            <div>
                <h2></h2>

                    <ins>  
<span>DHs</span>
Dhs   
</ins>
            </div>
@endforeach



via Chebli Mohamed