sevenTopo

sevenTopo

web developper at NJT MARRAKECH

Member Since 4 Months Ago

MARRAKECH

Experience Points
2,620
Total
Experience

2,380 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
17
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
2,620 XP
Jan
25
1 month ago
Activity icon

Started a new Conversation Laravel Passport .Route [login] Not Found

Hi Everyone.

When i try to access to any route in my Api.php file using Postman im facing this error ' Route [login] not defined.in file ....\Illuminate\Routing\UrlGenerator.php on line 420. so before anything i have to notice that im using Laravel Passport package ,following the Laravel Documentation https://laravel.com/docs/6.x/passport.

this is My Api.php file


Route::post('login', '[email protected]');
Route::post('register', '[email protected]');

Route::group(['middleware' => 'auth:api'], function(){
        Route::resource('/task', 'TaskController');
        Route::resource('/category', 'CategoryController');
        Route::get('/category/{category}/tasks', '[email protected]');
    });

and this is on of my controllers TaskController store function for exemple.


/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $task = Task::create([
            'name' => $request->name,
            'category_id' => $request->category_id,
            'user_id' => $request->user_id,
            'order' => $request->order
        ]);

        $data = [
            'data' => $task,
            'status' => (bool) $task,
            'message' => $task ? 'Task Created!' : 'Error Creating Task',
        ];

        return response()->json($data);
    }

And for Laravel Passport Configuration : i have my AuthServiceProvider with the necessary imports

 /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
   public function boot()
    {
        $this->registerPolicies();

        Passport::routes();
    }

config/auth.php

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

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

i did what it should be done so what is the problem guys . thanks for taking the time and effort before anything .

Jan
15
1 month ago
Activity icon

Started a new Conversation Laravel Chartist-js To PDF

Hi everyone .

i was wondering if it's possible to convert a chart built with chartistjs to pdf using laravel pdf paquage or any other php librarie .

i tried to use the html2canvas librarie but unffornutally it doesn't work . it shows only the block div (empty) .

that's the view represent the chart : https://ibb.co/kqV7wnL.

this my view

 <div class="table-wrapper" id="table-wrapper" style="display: block">
        <table id="datatable1" class="table display table-striped table-bordered table-hover responsive nowrap">
            <thead class="bg-info">
                <tr>
                    <th class="wd-15p">{{__('jour')}}</th>
                    <th class="wd-15p">{{__('matin')}}</th>
                    <th class="wd-15p">{{__('soir')}}</th>
                </tr>
            </thead>
            <tbody id="tb">
               <tr>
                 <td>{{$date_debut}}</td>
                 <td>{{$x_data_matin_debut}}</td>
                 <td>{{$z_data_matin_fin}}</td>
               </tr>
                <tr>
                 <td>{{$date_fin}}</td>
                 <td>{{$y_data_soir_debut}}</td>
                 <td>{{$a_data_soir_fin}}</td>
               </tr>
            </tbody>
        </table>
        <br>
        <div class="col-lg-10 pull-right">
          <ul class="nav nav-pills pull-right">
            <li class="nav-item">
            <input class="btn btn-outline-dark mg-r-5" value="{{__('Imprimer')}}">
          </li>
          </ul>
        </div>
        
    </div>
    <div id="ct-chart" style="display:block">
      <div class="tct-chart" id="tct-chart"></div>
      <ul class="nav nav-pills pull-right">
            <li class="nav-item">
            <input class="btn btn-outline-dark mg-r-5" onclick="chartPdf()" value="{{__('Imprimer')}}">

            <a href="{{url('/testPdf?date_debut='.$date_debut.'&date_fin='.$date_fin.'&x_data_matin_debut='.$x_data_matin_debut.'&z_data_matin_fin='.$z_data_matin_fin.'&y_data_soir_debut='.$y_data_soir_debut.'&a_data_soir_fin='.$a_data_soir_fin)}}" >Imprimer</a>
          </li>
          </ul>
    </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<script src="http://hongru.github.io/proj/canvas2image/canvas2image.js"></script>
<script>
 function chartPdf()
  {
    alert('hellow');
    html2canvas(document.querySelector(".ct-chart")).then(canvas => {
    document.body.appendChild(canvas)
    to_image(canvas);
  }

  //to image 
 function to_image(canvas){
  alert('start canvas to image')
               // var canvas = document.getElementById("thecanvas");
                document.getElementById("theimage").src = canvas.toDataURL();
                Canvas2Image.saveAsPNG(canvas);
            }

  function showGraphe()
  {
   // alert('clicked')
    document.getElementById('ct-chart').style.display = "block";
    document.getElementById('table-wrapper').style.display = "none";
  }
  function showTable()
  {
   // alert('clicked')
    document.getElementById('table-wrapper').style.display = "block";
    document.getElementById('ct-chart').style.display = "none";
  }
  let val_deb_matin = {!! $x_data_matin_debut !!} ;
  let val_deb_soir = {!! $y_data_soir_debut !!} ;
  let val_fin_matin = {!! $z_data_matin_fin !!} ;
  let val_fin_soir = {!! $a_data_soir_fin !!} ;
  let val_date_debut = {!! $date_debut !!} ;
  let val_date_fin = {!! $date_fin !!} ;
  new Chartist.Bar('.tct-chart', {

  labels: [val_date_debut,val_date_fin],
  series: [
    [val_deb_matin,val_deb_soir],
    [val_fin_matin,val_fin_soir],
  ]
}, {
  // Default mobile configuration
  stackBars: true,
  axisX: {
    labelInterpolationFnc: function(value) {
      return value.split(/\s+/).map(function(word) {
        return word[0];
      }).join('');
    }
  },
  axisY: {
    offset: 20
  }
}, [
  // Options override for media > 400px
  ['screen and (min-width: 400px)', {
    reverseData: true,
    horizontalBars: true,
    axisX: {
      labelInterpolationFnc: Chartist.noop
    },
    axisY: {
      offset: 60
    }
  }],
  // Options override for media > 800px
  ['screen and (min-width: 800px)', {
    stackBars: false,
    seriesBarDistance: 10
  }],
  // Options override for media > 1000px
  ['screen and (min-width: 1000px)', {
    reverseData: false,
    horizontalBars: false,
    seriesBarDistance: 15
  }]
]);

</script>


Jan
12
1 month ago
Activity icon

Replied to Laravel Bootstrap Auth Doesn't Create Auth Controller

what version of laravel are u using ?

Dec
12
2 months ago
Activity icon

Replied to Restful API

this a github project about Laravel Rest API with ionic check the structure of project ,it helped me so much .

Activity icon

Replied to Auth:: Or Auth()

both ..no difference .

Activity icon

Replied to Laravel Rest Api: This Request Has No Response Data Available

Done.thank you so much for your time

Dec
11
2 months ago
Activity icon

Replied to Laravel Rest Api: This Request Has No Response Data Available

Thank you so much for your help i fixed the probleme .i created a BaseController .

<?php

namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;

class BaseController extends Controller
{
public function sendResponse($result , $message){
$response = [
'success' => true ,
'data' => $result,
'message' => $message
];
return response()->json($response , 200);
}
}

and in my UserController or any X controller you i did that :



namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Api\BaseController as BaseController;
use App\Role;
use App\User;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
    header('Access-Control-Allow-Methods : POST, GET, OPTIONS, PUT, DELETE, HEAD');
    header('Allow: POST, GET, OPTIONS, PUT, DELETE, HEAD');
    header('Access-Control-Allow-Headers : X-Requested-With, Content-Type');
class UserController extends BaseController
{
    
    public function authenticate(Request $request)
    {   
         $credentials = json_decode($request->getContent(),true);
        //$credentials = $request->only('email', 'password');
        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 400);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        $user = User::where('email',$credentials['email'])->first();
        $roles=Role::where('user_id',$user->user_id)->get();
        if($user)
        {
         return $this->sendResponseLogin($token,'success',$user,$roles);
        }else{
         return $this->sendError('invalid_credentials','mot de passe ou login erroné');
        }

}

}

so this version of code it works it return a response with json data ..why ?? im not sure .

Activity icon

Replied to Laravel Rest Api: This Request Has No Response Data Available

oh sorry don't worry about it .that is not the problem

Dec
10
2 months ago
Activity icon

Replied to Laravel Rest Api: This Request Has No Response Data Available

Yes im sure ,it works fine with postman ;i changed the browser to mozila but im facing the same probleme .

im not sure if the probleme is releated to cors plocies . i added

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
header('Content-Type: application/json');
class UserController extends Controller
{
 public function login()
{
////
}
}

to my controller . but no results. i'm struggling with it .

Activity icon

Replied to Laravel Rest Api: This Request Has No Response Data Available

yes i did but no response att all . the only way is to use Response()->json($emailOrPasswordNotanObject);

Activity icon

Started a new Conversation Laravel Rest Api: This Request Has No Response Data Available

hi developers . it's my first time with rest api ,using laravel as a backend .

so the probleme is that i can't achieve to return my data ($users) for exemple.,it returns this message in

browser console "this request has no response data available".

so first this is my route in routes/api.php :

Route::middleware('jwt.auth')->get('users', function () {
    return auth('api')->user();
});

Route::post('/testlogin', 'Api\[email protected]'); //this is my route 
  

for my controller app/http/controllers/Api/TestController :

     public function login()
    {  


    try {
        $postdata = json_decode(file_get_contents("php://input"), true);
        $credentials['email'] = $postdata['email'];
        $credentials['password'] = $postdata['password'];
         if (!$token = auth('api')->attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
             }
             $data=array();
             $data['token']=$token;
             $data['expires']=auth('api')->factory()->getTTL() * 60;

             //when i return response()->json($data['token']); it show's the the token but when i return response()->json(['data'=>$data]); no response at all.
             return response()->json($data);
    } catch (Exception $e) {
         return response()->json("error");
    }  
    
    }

Nov
21
3 months ago
Activity icon

Replied to Laravel ,Factory Tinker

you are a real man .it work's perfectly

Activity icon

Started a new Conversation Laravel ,Factory Tinker

hi everyone: i'm trying to insert some data into my database with tinker .and im facing this error now :

PHP Warning:  Illegal string offset 'location_id' in C:/*/**/***/vendor
/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 584.

here is my Boxe Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Boxe extends Model
{
    // Define Table
    /*public $table = 'boxes';*/

    protected $fillable = [
        'location_id', 'customer_id','box_name', 'box_key', 'box_type',
    ];

    // Disable Timestamps
    public $timestamps = false;

    // Define The Primary Key
    protected $primaryKey = 'box_id';
    protected $attributes ="active";
    
    
}

and this is my Boxe Factory :

<?php

use Faker\Generator as Faker;

$factory->define(App\Boxe::class, function (Faker $faker) {
    return [
        "location_id"=>$faker->randomDigitNotNull,
        "customer_id"=>$faker->randomDigitNotNull,
        "box_name"=>"NJTBoxe".$faker->name,
        "box_key"=>$faker->bothify('##??'),
        "box_type"=>$faker->numberBetween(0,3),
        "active"=>$faker->numberBetween(0,2),
    ];
});


and that's the error:

$ php artisan tinker
Psy Shell v0.9.9 (PHP 7.3.9 — cli) by Justin Hileman
>>> factory('App\Boxe',50)->create();
PHP Warning:  Illegal string offset 'location_id' in C:/*/**/***/project/vendor
/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php on line 584

Note that i created some other factories without problems ,and i guess that the error is beacause of my model configuration.

Nov
18
3 months ago
Activity icon

Replied to Laravel Rest Api Web And Mobile

Thank you guys for your help.i choosed Nakov 's solution . returning two tipes of data and depending to my request if it need json response i'll return json if it's not by default returning a blade with my array(data) for exemple . thank you all.

Nov
17
3 months ago
Activity icon

Started a new Conversation Laravel Rest Api Web And Mobile

Hello every one ,i have an existing web application created with laravel wich all the controllers return views (blades) with data etc...

for now everything work fine but i'm plaining to use those services for a mobile app using the REST API .how can

i do that without recreating a copy of my controllers or routes ..(i want to use the same routes and controllers ).

do you have any idea guys.

Nov
13
3 months ago
Activity icon

Replied to Laravel File_put_contents(..../session/....) Failed To Open Stream

ok after 4 hours of searching ,i found a solution . so I went to my projecdirecoryt/bootstrapp/cache.php and deleted config.php then recreated a new config.php

Activity icon

Replied to Laravel File_put_contents(..../session/....) Failed To Open Stream

ok i will take a look on that .thank you

Activity icon

Replied to Laravel File_put_contents(..../session/....) Failed To Open Stream

yah obviously that's the issue ,how can i change it to the path server and where i can do that ?

Activity icon

Started a new Conversation Laravel File_put_contents(..../session/....) Failed To Open Stream

Hi again . i started to upload my project to a hosting server.but there is always new bugs and( im the lucky one).

will my probleme is so clear first there is this message append when i try to access to subdomain

file_put_contents(C:\xampp\htdocs\njt_private_project\thermo\storage\framework/sessions/JyNXpbnsmCU6vLK2OsPVRHPaQmvMQK5YIem2QXUt): failed to open stream
```.
so as i understand laravel still use my local cache even in the server .so how can i fixe this issue mannualy  .

Note(i don't have access to the terminal in my serve so i can't clear or config or run in artisan command)
Activity icon

Replied to File_put_contents(C:\xampp\htdocs\xxx\storage\framework/sessions/KXcxw0bXfbUEyvf2fCN12hiHt9VFeWTFFEzS42rk): Failed To Open Stream: No Such File Or Directory

Ok i don't have any terminal or git in server ,can i make this modifications in my local then try to upload it if it's yes plz how can i do it.

Nov
06
3 months ago
Activity icon

Replied to Laravel & Migrations

you are my hero .thank you you saved me . and it's working fine

Activity icon

Started a new Conversation Laravel & Migrations

hi every one ,hope you doing good guys .

i have a probleme with the user table(migration) .I tried to customise my user migration so instead of using the id ,i used user_id .but when i try to validate a user register i got this probleme .i perfectly undersatnding the problem but im not sure how to fix it .

  public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('user_id');
            $table->tinyInteger('admin')->comment="0:user, 1:admin";
            $table->string('email',100)->unique();// l'attribut login dans la conception represente l'email 
            $table->string('password',40);
            $table->string('name',40);
            $table->datetime('last_login');
            $table->datetime('create_date');
            $table->tinyInteger('status')->default(1)->comment="0:not active, 1:active, 2:suspended ";
            $table->string('token',100)->nullable();
            $table->datetime('token_date');
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
          
        });
    }

and that's the error :

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `users` where `id` = 1 limit 1)"
Nov
05
3 months ago
Activity icon

Replied to Laravel And Foreign Keys

Thank you so much .now i can see the difference .

Nov
03
3 months ago
Activity icon

Started a new Conversation Laravel And Foreign Keys

Hi every one .

i'm trying to create a database with some relationships bitwen 3 tables ,using the laravel docementation . my question is relate to sql :

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

what is the difference bitwen those 2 lines and what you guys recommanding ?

Oct
26
4 months ago
Activity icon

Replied to How To Click On A Li


  ///you can use jquery 

$("li .dropdown__menu__item ").click(function(){

   console.log("do something")
})

Oct
25
4 months ago
Activity icon

Replied to Laravel And Vendor

yes it looks bad ...and installing vendor all the time for every project is bad too

Activity icon

Started a new Conversation Laravel And Vendor

Hi developper i was wondering if it's possible to move the vendor folder outside of the project and make it global for all the projects just like :

   htdocs:
               ->vendor 
              ->laravel_project 1
              ->larvel->project 2 ....etc.

if it's possible how can i force the composer to not install the vendor cause we allready have a vendor for all the projects .

Activity icon

Replied to How To Update Image With AJAX In Laravel

to edit the image you have to delet it first and upload another image instead of it .that's the principe of edeting an image .

Oct
24
4 months ago
Activity icon

Replied to Laravel Registre Route

thank you that's so helpful

Activity icon

Replied to Laravel Registre Route

the probleme is that i want to use this route in the dashboard admin to create some new profiles .

Activity icon

Replied to How To Update Image With AJAX In Laravel

let's suppose that this is your view with a list of images :

@foreach($imgs as $img)
<div class="img-wrap" id="{{$id}}" >
                                  <span class="close" onclick="deletImage('{{$id}}','{{$img}}')">&times;</span>
                                  <img id="id{{$img}}" class="ggg" src="{{url('img/uploads/'.$img)}}" width="75" height="75">
 </div>
@endforeach

tha javascipt function deleteImage have the parametre {{$img}} wich i want to delete so fisrt lets hide all the div

 function deletImage(i,x)
   {
    confirm("Are You sure want to delete !");
//hide the the element 
    $('#'+i).remove();
///specifie the URl for your route and the methode delete    
    $.ajax({
      url:'{{url("/remove/img")}}'+'/'+x,
      data:{"_token": "{{ csrf_token() }}",extension:x},
      type:'DELETE',
      success:function(data)
      {
          console.log(data);
       }, 
       error: function (data) {
                console.log('Error:', data);
            }
    });
   }

my route :

Route::delete('/remove/img/{id}','[email protected]')->name('deletImage');

and finally make your remove function

public function remove(Request $request)
    {
 //change the directory by yours
      $img_find=public_path('img/uploads/')."".auth()->user()->id."/".$request->extension;
      if (File::exists($img_find)) {
       File::delete($img_find);
       return  response()->json(['success'=>'Got Simple Ajax Request.'.$img_find]);
      }
      return  response()->json(['error'=>'image not found.'.$img_find]);
    }

Activity icon

Started a new Conversation Laravel Registre Route

How can i hide the registre route and make it visible only for admins ?

Oct
21
4 months ago
Activity icon

Replied to The File "C:\xampp\tmp\php8911.tmp" Does Not Exist

so what is the solution in this case

Activity icon

Replied to 419 Page Expired

hi .make sure that you added {{csrf_field()}} in inside the form action ?

Oct
20
4 months ago
Activity icon

Replied to Images Are Being Storing As .tmp ?

you can do that:

 
foreach ($request->file('cheque_image') as  $key=> $file) {
              $image->move(public_path('img/uploads/'), $image->getClientOriginalName());
              $content["name"][]=$image->getClientOriginalName();
            } //if you are trying to store the data in DB i suggest to use json_encode 
 $content["name"] = json_encode($content["source"]);
Oct
15
4 months ago
Activity icon

Replied to Laravel Uploading A .tmp File Instead Of Image

will i had the same probleme today ...in my view i have input with name "image" when i tried to upload it and move it after i got the same error so my solution was so simple i have to recuperate the name of my image and the extension and put the file in my storage directory (public_path).

$request->file('image')->move(public_path('img/test'),$request->file('image')->getClientOriginalName().".".$request->file('image')->getClientOriginalExtension()); return $request->file('image')->getClientOriginalName();