mardi 30 juin 2020

I want the follower key to be true too... in my mutual friend query

Here is the query. Basically i am passing two parameters user_id (logged in user) and friend_id so the query will fetch all friends imagine you are click on your own friend and seeing the friend on another screen some are mutaul friend.. in this query mutaul is fine.. but when i want to follow the person that is not followed by the firned_id i need that to be true when there is exists data against the user_id

here im checkign relationship between user_id=334 and friend_id=312 image i have friend_id have these friend 1,2,3 and user(logged in user) has 3, 4, 5 now 3 is mutal friend that is toally fine and my ismutaul=1

now there is a record against the friend 2 in followers table in database so friend 2 actually is the friend of 312 and 312 not following. so how can i make it true because 334 is already follwoing him i need the isfollower varaible to be true.

im stuck and i dont know what to do any help please?

SELECT 
    users.id AS user_id,
    users.username,
    CONCAT('/',
            IF(users.photo = '',
                'default_image.png',
                users.photo)) AS user_image,
    users.phone,
    (SELECT 
            COUNT(user)
        FROM
            meal_rating
        WHERE
            user = users.id AND comment <> '') AS checkin_count,
    (CASE
        WHEN
            uf.receiver = (SELECT 
                    receiver
                FROM
                    user_friends
                WHERE
                    sender = 312 AND receiver = uf.receiver
                        AND user_friends.receiver IN (SELECT 
                            receiver
                        FROM
                            user_friends
                        WHERE
                            sender = 334))
        THEN
            1
        ELSE 0
    END) AS isMututal,
    CASE
        WHEN
            uf.receiver = (SELECT 
                    receiver
                FROM
                    user_followers
                WHERE
                    sender = 312 AND receiver = uf.receiver)
        THEN
            1
        ELSE 0
    END AS isfollowers,
    users.*
FROM
    `users`
        INNER JOIN
    `user_friends` `uf` ON `users`.`id` = `uf`.`receiver`
WHERE
    `uf`.`sender` = 312 
UNION SELECT 
    users.id AS user_id,
    users.username,
    CONCAT('/',
            IF(users.photo = '',
                'default_image.png',
                users.photo)) AS user_image,
    users.phone,
    (SELECT 
            COUNT(user)
        FROM
            meal_rating
        WHERE
            user = users.id AND comment <> '') AS checkin_count,
    (CASE
        WHEN
            sender = (SELECT 
                    sender
                FROM
                    user_friends
                WHERE
                    receiver = 312 AND sender = uf.sender
                        AND sender IN (SELECT 
                            sender
                        FROM
                            user_friends
                        WHERE
                            receiver = 334))
        THEN
            1
        ELSE 0
    END) AS isMututal,
    CASE
        WHEN
            uf.sender = (SELECT 
                    sender
                FROM
                    user_followers
                WHERE
                    sender = 312
                        AND user_followers.receiver = uf.sender)
        THEN
            1
        ELSE 0
    END AS isfollowers,
    users.*
FROM
    `users`
        INNER JOIN
    `user_friends` uf ON `users`.`id` = `uf`.`sender`
WHERE
    `uf`.`receiver` = 312


via Chebli Mohamed

add zero after point in Laravel

I am trying to add zero after point. For Example if price is 18 then I want to convert into 18.00 For this I am using Number Format and this is working.Below code is working perfectly. But problem is that, if price is 19.07 then its prints like 19.07999999998.

 Blade::directive('money', function ($amount) {
        return "<?php echo '$' . number_format($amount, 2); ?>";
    });
         if($this->app->environment('production'))
         {
             $this->app['request']->server->set('HTTPS','on');
            }
    
        }


via Chebli Mohamed

Laravel sms verfiction api using firebase sms without using twilo or nexmoo

Can i use firebase sms verfiction in a laravel restful api to send code to users without using third party libraries such as twilo or nexemo



via Chebli Mohamed

Laravel - Relations - Why works this way of accessing properties?

I've got a question regarding the laravel framework (version 5.2). This is not my code, but I need to understand why and how this works for a customer. I do not understand why I can access properties of a model the following way. I have a controller, which opens a blade template (view) this way:

return view("elements.base")
       ->with("html", getTypo3HtmlTemplate(view('Modul.'.$modul->getOriginal('bezeichnung'))
       ->with('modul',$modul)
       ->with('isCustomer', ($modulLaufzeit != null || \Auth::user()->benutzerFunktion_FK == 2 ? 1 : 0))
        ->render(),$modul->bezeichnung));

As you can see there are only 2 parameters given (modul and isCustomer). modul is model coming from the database.

The model class looks like this:

<?php
class Modul extends \App\Models\Base\BaseModel
{
    public $table = "tbl_Modul";

    public function __construct()
    {
        $this->relationMethods[] = "felder";
    }

    public function getBezeichnungSpecialChars($loadGermanLanguage = false) {
        ...
    }

    public function getBezeichnungSpecialCharsNonHTML($loadGermanLanguage = false) {
        ...
    }

    private function getKostenpflichtigeModule() {
        return $this->query()->where('paket', 0)->where('modulKostenlos',0)->where('inEntwicklung',0)->get();
    }

    public function getModulPaketbezeichnung($html = true, $loadGermanLanguage = false) {
        ...
    }

    public $laufzeit = 0;

    public function felder()
    {
        return $this->hasMany(\App\Models\Feld\Feld::class,"modul_fk");
    }

    public function zulassung()
    {
        return $this->hasOne(\App\Models\Zulassung\Zulassung::class,'id','zulassung_fk');
    }

    public function vorschrift()
    {
        return $this->hasOne(\App\Models\Vorschrift\Vorschrift::class,'id','vorschrift_fk');
    }

    public function demo()
    {
        return $this->hasOne(\App\Models\Modul\ModulDemo::class,'id','modul_demo_fk');
    }

    public function demokostenlosebemessung()
    {
        return $this->hasMany(\App\Models\Modul\ModulDemoKostenloseBemessung::class, 'modul_fk');
    }

    public function modulpreise()
    {
        return $this->hasMany(\App\Models\Modul\ModulPreis::class,"modul_fk");
    }

    public function version()
    {
        return $this->hasMany(\App\Models\Modul\ModulVersion::class, 'modul_fk');
    }

    public function formeln(){
        return $this->hasMany(\App\Models\Formel\Formel::class, 'modul_fk');
    }
}

Now back to my initial question. In the blade template (view) the following code is being used:

@foreach ($feld_holzart->inhaltsTypen as $inhaltsTyp)
   ...
@endforeach

How can a variable $feld_holzart being used, when it is not given explicitly by the controller to the view? I thought, it only can be used this way:

@foreach ($modul->feld->holzart->inhaltsTypen as $inhaltsTyp)

I know there is a relation to felder, but nott to feld. I can't get it, how this works!? Can anybody explain to me how this is working? If you need more info, please let me know. I will try to provide these as soon as possible. Many, many thanks in advance!



via Chebli Mohamed

Unable to create Contact with xero API . Giving 401 Unauthorized Error?

I am trying to create contact on Xero with help of Wrapper library webFox/laravel-xero-oauth2 which giving this error

[401] Client error: PUT https://api.xero.com/api.xro/2.0/Contacts?summarizeErrors=true resulted in a 401 Unauthorized response: {"Type":null,"Title":"Unauthorized","Status":401,"Detail":"AuthorizationUnsuccessful","Instance":"d5f847cb-199e-405e-982 (truncated...)

This library is creating account on xero perfectly but giving error when try to create Contact.

$apiInstance             = resolve(\XeroAPI\XeroPHP\Api\AccountingApi::class);
    
$contact = new \XeroAPI\XeroPHP\Models\Accounting\Contact;
$contact->setName('asdrtfgbhunjmkl,kmjhnbgbbnbjbbj');
$contact->setContactId('6d42f03b-181f-43e3-93fb-2025c0hjhe92');

$apiResponse = $apiInstance->createContacts($xeroCredentials->getTenantId() ,$contact,true);
$message = 'New Contact Name: ' . $apiResponse->getContacts()[0]->getName();



via Chebli Mohamed

Laravel Eloquent Relationship with different foreign key

Laravel version is 7.0:

I have setup model relationships like this.

<?php

namespace App;


class Template extends Model
{

    protected $fillable = ['header_id', 'content', 'name'];

    public function header()
    {
        return $this->belongsTo('App\Header', 'header_id');
    }
}

In controller I can get template object with header.

<?php

namespace App\Http\Controllers;
use App\Template;

class TemplateController extends Controller
{

   public function show($id)
   {
     $template = Template::find($id);
   }
}

Now I can use $template->header in view.

How can I pass different header_id and get header relationship object? I would like to do as following:

<?php

namespace App\Http\Controllers;
use App\Template;

class TemplateController extends Controller
{

   public function show($id, $temp_header_id)
   {
     $template = Template::find($id);
     $template->header_id = $temp_header_id;
   }
}

I want to get new header relationship in view:

Is there any way to return new header relationship when I do $template->header in view.

Thank you



via Chebli Mohamed

Laravel Create Order using API

I'm building an API for e-commerce app

now, i get stuck in creating order

i have the following Migrations

Orders

        Schema::create('orders', function (Blueprint $table) {
        $table->id();
        $table->string('order_number');
        $table->unsignedBigInteger('user_id');
        $table->enum('status', ['pending','processing','completed','decline'])->default('pending');
        $table->float('grand_total');
        $table->integer('item_count');
        $table->boolean('is_paid')->default(false);
        $table->enum('payment_method', ['cash_on_delivery'])->default('cash_on_delivery');
        $table->string('notes')->nullable();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->timestamps();
    });

Order_items

        Schema::create('order_items', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('order_id');
        $table->unsignedBigInteger('product_id');

        $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');

        $table->float('price');
        $table->integer('quantity');

        $table->timestamps();
    });

Products

Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('img');
        $table->string('name');
        $table->string('desc');
        $table->integer('price');
        $table->timestamps();
    });

and this is Models Relationship

Order Model

public function items()
{
    return $this->belongsToMany(Medicine::class, 'order_item','order_id','product_id')->withPivot('quantity','price');
}

public function user()
{
    return $this->belongsTo(User::class);
}

Controller

    public function store(Request $request)
{

    $order = new Order();
    $order->order_number = uniqid('ORD.');
    $order->user_id = 1;
    $order->item_count = 2;
    $order->grand_total = 20;
    $order->save();

    return response(['message'=>'successful']);
}

Now, i can add Orders successfully .

but how to add items from JSON Request

for example by posting JSON Data from Postman

any ideas?



via Chebli Mohamed

handle banners in index page laravel

I have a shop project in Laravel. In my index page i have some banners :

4 banners in 1 row Banner 1 2 banners in 1 row Banner 2 1 banner in 1 row Banner 3

as you can see, i have some banners in different places, i don't know how can i handle banners in admin panel and show in index page, The only way that came to my mind is that make controller and model for each banner, but i think it's not normal way.

can you guide me how can i do this in Laravel ?



via Chebli Mohamed

Laravel Eloquent Connect two tables set condition in last row of second table if this condition true than it will return in my array

I have two tables one is order and second is order_status. Order table has details of order. Order Status has Order's Status with timestamp when it will changed.

Order table

enter image description here

order_status table

enter image description here

I mean that order has multiple status in order_status.

I want to filter my order list table by order status.

If i want orders which are delivered (all orders whose last status is delivered) How can i achieve that?

I am using laravel 5.8 Eloquent.



via Chebli Mohamed

lundi 29 juin 2020

Laravel 5.5 redirect back with input and error not working on production

My code does a simple redirect back with input and error if a doesn't enter a field correctly. This works on my local development environment just fine and the "old" inputs are populated in the form along with the error beneath the form field.

The live site is on a AWS server and forge was used to get it up and running. Please let me know if this is an issue with AWS or forge or I'm missing something to get it working on production.

    $v = Validator::make($data, [
        'fname' => 'required|string',
        'lname' => 'required|string',
        'title' => 'required|string',
        'email' => 'required|email|unique:users,email',
        'password' => 'required',
        'password-check' => 'required',
        'g-recaptcha-response' => 'required',
        'terms' => 'required',
        'service' => 'required',
        'captcha' => 'required|min:1'
    ]);
    if ($v->fails()) {
        return redirect()->back()->withInput()->withErrors($v->errors());
    }


via Chebli Mohamed

Suddenly show only index page in laravel 5.8

My websites in live server and it's working perfectly from march till today. Few hours i saw an error and that is it shows only index page nothing else. It did not reach any kind of URL and it just show the same problem. I did not understand what is happening suddenly. In the below, I gave an image of my problem.

HERE THE IMAGE OF THIS PROBLEM



via Chebli Mohamed

How to get the email senders name from the contact form - Laravel Mail

How can i change the Mail Subject, Title and the senders name from the form input fields,

Here's my contact form

<h1>Contact</h1>
<form action="contact/store" method="post">
    @csrf
    <label>Name</label>
<input type="text" name="name" placeholder="Name">
<br>
<label>Email</label>
<input type="email" name="email" placeholder="Email">
<br>
<label>Message</label>
<textarea name="message" cols="30" rows="10"></textarea>
<button type="submit">Submit</button>
</form>

Here's my Mail controller

public function store(Request $request)
{
    $name = $request->name;
    $email = $request->email;
    $textmessage = $request->message;

    $data = array('name' => $name, 'email' => $email, 'textmessage' => $textmessage);
    Mail::send('mail', $data, function ($message) {
        $message->to('jareerzeenam.29@gmail.com', 'Email Title')->subject('Test Subject 2');
        $message->from('test@gmail.com', 'Test Name 2');
    });
    echo "HTML Email Sent. Check your inbox.";
}

Here's my mail.blade.php

    <h1>Hi, i'm </h1>
<p>Email :</p>
<p>Message : </p>

Here's how i get the email as

email screen shot

How can i get the name from the contact form input field to my email instead of the static name i have given in the controller, hope my question is understandable.



via Chebli Mohamed

Use a default laravel validation rule inside custom rule file

I want to validate that my input is either UUID or "LAST_QUESTION". I created a custom validation rule LastOrUUID and I would like to use UUID validation rule inside of it. I could not find any way to do that, maybe you know what is the right way to implement this? My custom rule for context:

class LastOrUUID implements Rule
{
    /**
     * Determine if the validation rule passes.
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        if ($value === 'LAST_QUESTION' /* || this is uuid */) {

            return true;

        }

        return false;

    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // TODO - add translation
        return 'This should either be the last question or have a reference to next question!';
    }
}


via Chebli Mohamed

Queue New row insertion requests in Laravel to ensure server-side validation and avoid Duplicates

I have a table("product") with few column , say ID, brand_name, code, country_code and countrywise_serial_number, created_at, deleted_at.

I make a ajax call from webpage to insert values in table. The code I have written in backend is:

public function addProduct(Request $request){

    $brand_name = $request->brand_name;
  

    $sNo = DB::table('product')->where('country_code',101)->orderByDesc('countrywise_serial_number')->limit(1)->get();
    if($sNo->count()<1){
        $sNo=1;
    }else{
        $sNo= ($sNo[0]->countrywise_serial_number)+1;
    }
 
    $getDigit= 1;

    for($num=$sNo;$num>10;$num++){
        $num= $num/10;
        $getDigit++;

    }
    
    $zerosrequired= 7- $getDigit;
    $zeroes=str_repeat("0",$zerosrequired);
    $code="PRO"."IND".date("y")."MD".$zeroes.$sNo; //EG:PROIND20MD0000001

    // check if record already exist to avoid duplicate  entry
    $checkExistence=DB::table('product')->where(function($query) use($code){
        $query->where('code', $code);
        $query->whereNull('deleted_at');

    })
    ->orWhere(function($query) use($brand_name){
        $query->where('brand_name', $brand_name);
        $query->whereNull('deleted_at');

    })->get(); 
   
   
    if($checkExistence->count()>0){

        $existingData = array(
            'code' => $checkExistence[0]->code,
            'name' => $checkExistence[0]->brand_name,
           
        );
        return ['message'=> "Duplicate Warning" , 'name'=>$existingData['name'], 'code'=>$existingData['code']];
        

    }
    


    try{
    DB::table('product')->insert(
        ['code' => $code, 'brand_name' => $brand_name,'countrywise_serial_number'=>$sNo]
    );

    return ['message'=>true];
    }
     catch(\Exception $e){

        return  ['message'=>false];
     }
}

The problem is if I click submit button multiple times, multiple ajax requests are called and multiple rows with duplicate values are inserted(i.e. with same code and brandName) without any validation which should not happen.

I am worried if it will also happen if request is made from two or more device at the same time(with same values),

For avoiding multiple click to submit button I tried using:

$('#addsubmit').attr("disabled",true); //addsubmit is the submit button ID

and

$('#addsubmit').off("click");

but none of them are working; Here is the js code for ajax call:

$("#submit-product").submit(function(event){
    //submit-product is form ID

    //event.preventDefault();
    //event.returnValue = false;
    event.preventDefault ? event.preventDefault() : (event.returnValue = false);
    event.stopPropagation()

    
    
    var token = "";
    var formData={
        'brand_name' : $('#brand_name').val(),
        '_token': token
 
    };
    console.log(formData)
    $.ajax({
        type : 'post',
        data: formData,
        datatype: 'json',
        url: "",
        success: function(result){
            

            if (result.message=="Duplicate Warning"){
                $('#errormessage').html("") 
                $('#errormessage').css('color', 'red');
                console.log("if")
                if ($('#med_code').val()== result.code &&  $('#brand_name').val()==result.name)

                $('#errorDetails').html("Brand Name and Code already registered.")

                else if($('#med_code').val()== result.code)
                
                $('#errorDetails').html("product Code already in Use.")

                else
                $('#errorDetails').html("product already registered.")
                
                modalName ="add";
                //$('#deleteMessageImg').attr('src','')
                $('#add-products').modal('hide');
                $('#error-modal').modal('show');
            }

            else if(result.message){
                
                $('#add-products').modal('hide');
                $('#add-success-product').modal('show');
                $("#submit-product").trigger("reset");
            }
            
        }

        

    })
    

})

The server side validation part works fine if I insert record one by one i.e. after completion of one request.

Is there any way to let laravel finish one request at a time and then process another?



via Chebli Mohamed

maatwebsite/excel Export In Laravel

How to set header value bold in maatwebsite/excel Export In Laravel ?And also how to bold specific raw and set background.



via Chebli Mohamed

Cant get Property from the model realtion Laravel

I got an issue when i use fooreach loop with 3 model realtion in 1 view

This is my Thread model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    protected $primaryKey = "id_threads";

    public function user(){
    
        return $this->belongsTo('App\User','id_users');
    }

    protected $fillable = [
        'id_users', 'threads',
    ];

    public function comment(){
        return $this->hasMany('App\Comment','id_threads');
    }
        
}

This is my Comment model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $primaryKey = 'id_comments';

    public function thread(){
        return $this->belongsTo('App\Thread','id_threads');
    }

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

    protected $fillable = [
        'id_threads', 'id_users', 'comments','status'
    ];
}

This is my index controller

    public function index()
    {
        $user = Auth::user();
        $comment = Comment::all();
        
        //Threads
        $threads = Thread::orderBy('created_at','desc')
        ->get();
        $hitung = $threads->where('id_users', '=',$user->id);
        
        
        return view('/home',compact('threads','hitung','comment'));
    }

And this is piece of my view

@foreach ($threads as $thread)
    <div class="media-body">
        <h5 class="mb-0"></h5>
            <div class="card-date mb-2">
                 at 
            </div>
        <input type="hidden" name="$id_threads" value="">
            
            <div class="card-delete mt-5">
                @if (Auth::user()->id==$thread->id_users)
                <a href="">Delete</a>
                @else
                
                @endif
            </div>
            <hr>
            <div class="media comment mt-3">
                <a class="mr-3" href="#">
                    

The Error comes when i want to show comment

And an error like this appears

Property [comments] does not exist on this collection instance. (View: D:\Jendro\Project Laravel\projectCO\resources\views\home.blade.php)

But when i just call the object only, like this

Thats no error appears, in my view a data set appears from the Comment model

[{"id_comments":6,"id_threads":54,"id_users":2,"comments":"asdqweasd","created_at":"2020-06-29 08:58:53","updated_at":"2020-06-29 08:58:53","status":"comment"}] 

It was same when i use to call user object, but threse no problem with user object when i call property of user's object

I was stuck in this issue, does anyone have solution for this issue ?



via Chebli Mohamed

Laravel URL rewriting and routing

I am coding a webapp based on laravel. But getting some difficulties in routing function. Can you help me by providing suitable code.

Lets start with a example.

User is on index page http://example.com On this page there is a list of urls that is dynamically generated.

Every url has a format like - http://example.com/messages?n=79688

here 79688 is message id.

It want the url to be like http://example.com/messages/79688

Here is web.php //Route for Messages

Route::get('/messages', 'HomeController@messages')->name('Messages');

Here is HomeController.php

public function messages(Request $request) 
{ 
    if(isset($request->n)) { 
        $number = $request->input('n'); 
        $number_check = Number::select('type')->where('number', $number)->first(); 
        $per_page = env('PER_PAGE', 15); 
        $query = Message::where('number', $number); 
        $messages = $query->orderBy('created_at', 'DESC')->paginate($per_page); 
        $messages->withPath('?n='.$number); 
        return view('messages')->with('messages', $messages)->with('number', $number)->with('count', $messages->total());
    } else { 
        return redirect()->route('Main')->with('error', "Message not found"); 
    } 
}

Can you please tell me how to modify this controller so that it can catch message id from url http://example.com/messages/79688



via Chebli Mohamed

Laravel passport - is there way to add custom data in access token

My laravel app is a multi tenant application, i am trying to add custom data to the laravel passport token other than user Model. is there any way to do it.



via Chebli Mohamed

dimanche 28 juin 2020

Switch case of object in PHP

I don't have a good knowledge in PHP. Will you please, anyone help me to implement a switch case or if else statement in a set of objects.

For example I have set of JSON object like below

 {"car":[{"colour":"black", "brand":"BMW", "owner":"rob"}]}
 {"bike":[{"colour":"red",  "brand":"Bajaj", "owner":"john"}]}
 {"cycle":[{"colour":"blue",  "brand":"Hero", "owner":"mike"}]}

My requirement is need to check it's car, bike or cycle. in the below example message is the random JSON object

$smsobj = json_decode($message, true);
switch ($smsobj) {
    case $smsobj->bike:
      $this->bike($smsobj);
      break;
    case $smsobj->car:
      $this->car($smsobj);
      break;
    case $smsobj->cycle:
      $this->cycle($smsobj);
      break;
      defualt: $resolver->acknowledge($message);
  }

when I received a car object I will get some error like this Trying to get property 'bike' of non-object

Thank you.



via Chebli Mohamed

samedi 27 juin 2020

Store product multiple colors to the database Laravel

I have a product table which has price, name, stock etc. and color_products table which has color_id, product_id. I want to store a product to the database with selected colors so far I'm getting an error Invalid argument supplied for foreach(). How can I fix this?

Controller

 $formInput=$request->all();   //If I do dd($formInput) I see all data

    $product = product::create(array_merge($formInput, [
        'user_id' => Auth::user()->id
    ]));
   
 // Insert color to the database

    $store_color = [];
    $colors = $request->color_id;

    foreach ($colors as $color) {
        $ouzColor = $color->save;
        $store_color[] = [
            'product_id' => $product->id,
            'color_id' =>  $ouzColor
        ];
    }
        ColorProduct::insert($store_color);

Blade file

  <select multiple name="color_id" id="color">
     <option value=""> --Select Colors -- </option>
         @foreach($colors as $color)
           <option value="" ></option>
         @endforeach
  </select>


via Chebli Mohamed

how to check relation value laravel?

im new using laravel and i get some problem.

i have function in my controller :

$user = auth()->user()->orders()->with('products')->get();
    //dd($user);
    if(!empty($user)){
        $order = $user->last()->products->pluck('details')->toArray();
        $details = implode(" ", $order);
        // dd($details);

        return $details;
    }else{
        //nothing
    }

i want check, if logged in user have relations product run the code and return value, if empty do nothing.

this is my user model :

 class User extends \TCG\Voyager\Models\User
{
    public function orders() 
    {
    return $this->hasMany('App\Order');
    }
}

this is my order model :

class Order extends Model
{
  public function user()
{
    return $this->belongsTo('App\User');
}

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('quantity');
}

}

the problem is how to check logged in user has relation product or not, if yes execute code and return value, if no do nothing. sorry for my broken english ,thanks.



via Chebli Mohamed

Iterating through array chunk for a function call

I have an array that has 20 objects in it (I have reduced this to 3 in this example to keep things simple).

    $dataset = array(
      array(
        "product" => $product->id,
        "unit_amount" => "2020",
        "end_date" =>  date_timestamp_get(date_create("2020-07-12")) // Payment 1 Date
    
      ),
      array(
          "product" => $product->id,
          "unit_amount" => "2000",
          "end_date" =>  date_timestamp_get(date_create("2020-07-15")) //Payment 2 Date
      ),
      array(
          "product" => $product->id,
          "unit_amount" => "3400",
          "end_date" =>  date_timestamp_get(date_create("2020-07-16")) //Payment 3 Date
      ),
)

I can split the array by using chunks:

$schedule_batch = array_chunk($dataset, 9);

Now I want to process each chunk as seperate calls

  foreach ($schedule_batch as $key => $value){
    foreach ($schedule_batch[$key] as $key2 => $value2) {
         createSchedule($customer->id, $phases);
      }
    }

However all this does it just process all of the 20 array items in one call. My goal is to allow it to run twice creating two schedules each with 10 items (not a schedule of 20 items).

Any help is really appreciated.



via Chebli Mohamed

how to change array structure in laravel?

Hello everyone i get some problem when try learn php with laravel, there is the problem ...

i have an array structure like this :

array:3 [▼
  0 => 16
  1 => 19
  2 => 15
]

how can u change the array structure to look like this :

array:3 [▼
  0 => array:1 [▼
    0 => 16
  ]
  1 => array:1 [▼
    0 => 19
  ]
  2 => array:1 [▼
    0 => 15
  ]
]

im newb ,can somebody help me, im using laravel 5.8 ,very grateful if someone helps. sorry for my broken english.



via Chebli Mohamed

How to replace request method with static? inRandomOrder

random requests greatly slow down the site, products change on the main site, with each update! I want to make it static! Here is the code! help me please!

public function index()
    {
      //homepage
      $settings =Setting::first();
      $credit = Credit::first();
      $rate_per_click = $credit->rate_per_click;
      //random products
      $products = Product::whereHas('user', function($q)use ($rate_per_click) {
        $q->where('credit', '>',$rate_per_click);
        $q->where('active', 1);
        })->inRandomOrder()->limit($settings->home_rand_pro)->get();
         //get 4 latest posts
      $posts = Post::orderBy('id', 'desc')->take($settings->home_posts)->get();
      $users = User::where('active', '=',1)->take($settings->home_users)->get();
      return view('index')
->with('latest_product',Product::whereHas('user', function($q)use ($rate_per_click) {
        $q->where('credit', '>',$rate_per_click);
        $q->where('active', 1);
        })->orderBy('id','desc')->first())
->with('most_viewed_product',Product::whereHas('user', function($q)use ($rate_per_click) {
        $q->where('credit', '>',$rate_per_click);
        $q->where('active', 1);
        })->orderBy('views_count','desc')->first())
->with('most_clicked_product',Product::whereHas('user', function($q)use ($rate_per_click) {
        $q->where('credit', '>',$rate_per_click);
        $q->where('active', 1);
        })->orderBy('click_count','desc')->first())
    ->with('categories',(Category::all()))
    ->with('pages',(Page::all()))
    ->with('slides',(Slider::all()))
    ->with('products',$products)
    ->with('posts',$posts)
    ->with('users',$users)
    ->with('settings',$settings);
    }

This code is on the product page!

//get random Products
      $rand_products = Product::whereHas('user', function($q)use ($rate_per_click) {
        $q->where('credit', '>',$rate_per_click);
        $q->where('active', 1);
        })->inRandomOrder()->limit(5)->get();
      return view('product_page')
      ->with('product',$product)
      ->with('compared_products',$compared_products)
      ->with('rand_products',$rand_products)
      ->with('categories',(Category::all()))
      ->with('pages',(Page::all()))
     ->with('settings',$settings);
    }

Sorry for my bad english!



via Chebli Mohamed

how to add value from another array?

I have 2 array and this array structur look like.

array 1:

array:21 [▼
  8 => 5.2611505021202
  21 => 1.9708761602636
  4 => 1.9691954688805
] 

array 2:

array:21 [▼
  8 => array:2 [▼
    "id" => 10
    "details" => "Intel Core i5 4GB 1TB"
  ]
  21 => array:2 [▼
    "id" => 14
    "details" => "Intel Core i5 8GB 2TB SSD Touch Bar"
  ]
  4 => array:2 [▼
    "id" => 4
    "details" => "Intel Core i7-8700 GTX1060 8GB 1TB SSD Win10"
  ]
]

the problem is, how can u combine that array and make new array like this :

array:21 [▼
  8 => array:2 [▼
    "id" => 10
    "details" => "Intel Core i5 4GB 1TB"
    "score" => 5.2611505021202 //value from array 1 and input the value to same index [8] -> [8]
  ]
  21 => array:2 [▼
    "id" => 14
    "details" => "Intel Core i5 8GB 2TB SSD Touch Bar"
    "score" => 1.9708761602636 //value from array 1 and input the value to same index [21] -> [21]
  ]
  4 => array:2 [▼
    "id" => 4
    "details" => "Intel Core i7-8700 GTX1060 8GB 1TB SSD Win10"
    "score" => 1.9691954688805 //value from array 1 and input the value to same index [4] -> [4]
  ]
]

is that possible ?, im newb very grateful if someone helps. sorry for my broken english.



via Chebli Mohamed

vendredi 26 juin 2020

Array formatting in php (used laravel framework)

I am trying to format an array in php . It does not return in expected json format . Here is details.

$categories = category::where('cat_flag','Y')->pluck('cat_name as category_name')->toArray();
$items = item::leftjoin('categories','items.cat_id' ,'=', 'categories.id')
                      ->where('item_flag','Y')
                      ->get([
                            'item_name',
                            'items.cat_id as category_id',
                            'cat_name as category_name'
                        ])->toArray();

        $formatedArray = [];
        foreach ($categories as $category) {
            foreach ($items as $item) {
                if ($item['category_name'] == $category) {
                    $formatedArray['cat_name'] = $category;
                    $formatedArray['datas'][] = $item;
                }
            }
        }

my expected output is like bellow. but there is logical error in array format part . I am not getting properly how to format that. Thanks in advance

       [
         {
           "cat_name" : "food",
           "datas" : [
                {
                  "item_name": "item2",
                  "category_id": "1"
                },
                {
                  "item_name": "item4",
                  "category_id": "1"
                }
             ]
           },
           {
           "cat_name" : "drinks",
           "datas" : [
                {
                  "item_name": "coca cola",
                  "category_id": "4"
                }
             ]
           }
        ]

But my output showing like . All items are in same category

  {
"cat_name": "cat4",
"datas": [
    {
        "item_name": "item2",
        "category_id": "1"
    },
    {
        "item_name": "item22",
        "category_id": "2"
    }
 ]
}


via Chebli Mohamed

How to concatenate string to a $variable in blade?

I want to add a variable( in my case it is called $document) from my database to a URL asset directory in the view of my blade file to enable a user to view the image in the web browser. An example is as follows;

// MyController File

// the variable $code is a parameter I'm accepting from the web.php route file for 
// the function show() to help process the assignment value of $data['document'] without issues

public function show($code)
    {
        //  NB: I am passing the document as an array list item of $data as below, so I can mention it as 
        //  a variable in the blade view file 
        //  $data['document']

        $data['document'] = Auth::user()->documents->where("code", $code)->first();

        return view("documents.show", $data);
    }



// Blade View File

<div class="my-class" style="background: url() no-repeat center top; background-size: cover;">
</div> 


via Chebli Mohamed

SQLSTATE[3000]: Integrity constrain violation Laravel relations model

Good, I do not understand why when saving a record in my bd, this error appears to me, I have my migrations and my models, if I remove that key from my bd it saves the record well

model propertie

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Propertie extends Model
{
    //
    public function characteristic()
    {

        return $this->HasMany('App\Characteristic', 'property_id');
        
    }
    public function departament()
    {

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

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

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

        return $this->belongsTo('App\Offer_type','offer_type_id');
        
    }
    
    public function property_type()
    {

        return $this->hasOne('App\Property_type','id','property_type_id');
        
    }
    public function space()
{

    return $this->hasOne('App\Space', 'property_id');
    
}
    
     public function ImgProperties()
    {
        return $this->hasMany('App\ImgProperties');
    }
    
    protected $fillable = [
        'name', 'description', 'property_type_id', 'offer_type', 'spaces_id', 'departaments_id',
        'municipalities_id', 'details_id', 'characteristics_id', 'images','url', 'lat', 'lng','direction','price'

    ];
    
    public function scopeName($query, $name)
    {
        if($name){
            
             return $query->where('name', 'LIKE',"%$name%");
        }
       
    }
    
    public function scopeLatest($query)
    {
        return $query->latest();
    }
    
    public function scopeTypeOf($query, $type)
    {
        
        return $query->where('offer_type_id', 1);
    }
    
     public function scopeSortType($query, $type)
    {
        
        if($type == 'new'){
            return $query->latest();
        }
     }
    
    
    
}

model property_type

namespace App;
use App\Propertie;
use Illuminate\Database\Eloquent\Model;

class Property_type extends Model
{
        public $table = "property_type";

    protected $fillable = [
        'type_property'

    ];
    
    public function properties()
    {
        return $this->hasMany('App\Propertie');
    }

as you can see I have the relationships, a property can have a property type

property migration

    public function up()
    {
        Schema::create('properties', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable;
            $table->string('price')->nullable;
            $table->text('description')->nullable;
            $table->unsignedBigInteger('property_type_id')->nullable();
            $table->unsignedBigInteger('offer_type_id')->nullable();
            $table->unsignedBigInteger('spaces_id')->nullable();
            $table->unsignedBigInteger('departaments_id')->nullable();
            $table->unsignedBigInteger('municipalities_id')->nullable();
            $table->unsignedBigInteger('details_id')->nullable();
            //$table->unsignedBigInteger('characteristics_id')->nullable();
            $table->string('images')->nullable;
            $table->float('lat')->nullable;
            $table->float('lng')->nullable;
            $table->string('address')->nullable;
            
            $table->timestamps();
            
            $table->foreign('property_type_id')->references('id')->on('property_type');
            $table->foreign('offer_type_id')->references('id')->on('offer_type');
            $table->foreign('spaces_id')->references('id')->on('spaces');
            $table->foreign('departaments_id')->references('id')->on('departaments');
            $table->foreign('municipalities_id')->references('id')->on('municipalities');
            $table->foreign('details_id')->references('id')->on('details');
           //$table->foreign('characteristics_id')->references('id')->on('characteristics')->onDelete('cascade');

property type migration

 public function up()
    {
        Schema::create('property_type', function (Blueprint $table) {
            $table->id();
          
            $table->string('type_property');
            $table->timestamps();
        });
    }

    /**

if you can help me find the error i would appreciate it enter image description here



via Chebli Mohamed

Delete image in laravel through model relationship

.Multiplae images are stored from another model but i can not delete the images one by one. messedup in eloquent. how to delete the image with this model relationship

This is my product model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['title','image'];

    public function images(){
      return $this->hasMany('App\ProductImage');
    }
}

this is product image model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductImage extends Model
{
    public function product(){
      return $this->belongsTo('App\Product');
    }
}

This is view with delete link

@foreach($product->images as $image)
 <form class="product_image" action="" method="post">
@csrf
@method('DELETE')
    <img style="width:100%; height:100%;" src="">
        <button class="product_image_delete" type="submit">
           <i class="fa fa-trash" aria-hidden="true"></i>
         </button>
 </form>
@endforeach


via Chebli Mohamed

how to get data from relation laravel?

i have function ini my controller like this :

public function get_user_order() 
{
    $user = auth()->user()->orders()->with('products')->get();
    $order = $user->products->name;
    dd($order);
}

i want to get logged in user order history.

this is my user model:

class User extends \TCG\Voyager\Models\User
{
public function orders() 
{
    return $this->hasMany('App\Order');
}
}

this is my order model :

class Order extends Model
{
  public function user()
{
    return $this->belongsTo('App\User');
}

public function products()
{
    return $this->belongsToMany('App\Product')->withPivot('quantity');
}
}

the problem is how can u get the product name from this relation ? please help me im newb, sorry for my broken english.



via Chebli Mohamed

Replace '0' with 1 in phone numbers Laravel

I'm trying to replace users phone numbers to start with 1 instead of 0 but I'm stuck.

I have this line $mobileNumber = implode(',', $postData['phone']);

which outputs "0445329500,0569075729,0456786942" I want to replace all the first 0 with 1 so instead of 0445329500,0569075729,0456786942 it should be 1445329500,1569075729,1456786942

I have tried this Str::replaceFirst('0','1',$mobileNumber); it only replaces the first number 1445329500

Any help will be appreciated.



via Chebli Mohamed

how to get data from eager laravel?

i want to get logged in user history order, this my controller :

public function get_user_order() 
{
    $user = auth()->user()->orders()->with('products')->get();
    $order = $user->products();
    dd($order);
}

i get this error alert( Illuminate\Database\Eloquent\Collection::products does not exist.)

this is my user model :

class User extends \TCG\Voyager\Models\User
{
use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

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

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

public function orders() 
{
    return $this->hasMany('App\Order');
}
}

and this is my order model :

class Order extends Model
{
 
    public function products()
    {
    return $this->belongsToMany('App\Product')->withPivot('quantity');
    }

}

the question is , how can i get the product information and store it to array ?



via Chebli Mohamed

Too few arguments to function App\Http\Controllers\UsersController::edit(), 1 passed and exactly 2 expected

Too few arguments to function App\Http\Controllers\UsersController::edit(), 1 passed and exactly 2 expected

public function edit ($id , User $user) {
  $user = $user->find($id);
  return view('admin.user.edit',compact('user'));
}


via Chebli Mohamed

How to get related rows from attributes table assigned to a certain attribute in Laravel

I have category table, attribute table and attribute_value table,

Category:
id | Catgeory Name 

Attribute:
id| cat_id | Attribute Name

Attribute Table:
id | attr_id | attr_value

Now i want to Display it like this :

Category Name 
Attribute Name 1
Attribute Val 1
Attribute val n
Attribute Name 2
Attribute Val 1
Attribute Val n
..
..

I'm using following model

Attribute:

 public function attr_values()
  {
  return $this->hasMany(AttributeValue::class);
  }

Attribute Values :

 public function attribute()
   {
      return $this->belongsTo(Attribute::class);
   }

In controller i'm getting data using following:

Category::with(['attribute'])->whereIn('id', $ids)->get();

But i'm unable to get the data attributes that are linked to Category and its attributes Values.



via Chebli Mohamed

Reactjs and Laravel redirect issue

I'm newbie to laravel and react, I create frontend with reactjs and admin panel using laravel framework. Frontend is working fine and backend is in public folder. My issue is once run the frontend, i couldn't access the public folder.

Example:

http://www.example.com ---> working fine

http://www.example.com/react-first-url ---> working fine

http://www.example.com/react-second-url ---> working fine

but

http://www.example.com/public ---> Not working

Redirect to base url http://www.example.com/

Please help me and thanks in advance



via Chebli Mohamed

Laravel 5.2 Eloquent softdelete not working

I have a softdelete trait in my model. I've been trying to delete the file in db but is not working. Here's my model:

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use SoftDeletes;

    protected $table = 'files';

    protected $dates = ['deleted_at'];
}

My migration file:

public function up()
{
    Schema::table('files', function (Blueprint $table) {
        $table->softDeletes();
    });
}

And in my controller, I'm doing it this way.

$fileID = explode('/', $img)[1];

$JobImage = JobImage::where('file_id', $fileID)->update(['file_id' => null]); <- I'm updating first the column value of it's relationship to null, which works well.
$file = File::where('id', $fileID)->delete();

I don't understand if which part do I lack?



via Chebli Mohamed

How to fill an array in given format?

I want to form an array like this:

$routes = [
            array("key" => 0, "title" => "All"),
            array("key" => 1, "title" => "Web Series"),
            array("key" => 2, "title" => "Reality Shows"),
            array("key" => 3, "title" => "Singing"),
            array("key" => 4, "title" => "Vendors")
        ];

Here, the titles (web series, reality shows, singing) should come as a response from database:

    $projectTypes = ProjectType::select('project_type_title')->get()->all();

How to populate an array like above using these values ?

Note:

array("key" => 0, 
      "title" => "All") 

must be predefined and not fetched from database only other project types are fetched from the database



via Chebli Mohamed

Laravel how to pass null value in route parameter in front end

I have a form and I'm trying to pass null value into the $dev-id parameter but it doesnt work, instead ti will replace the dev id parameter with the $id as shown in my code at the bottom,

The reason i needed it to be null because I'm using this function for 2 different page but one of the page doesn't have $dev_id. any help is appreciated

HTML:

<form method="post"
    action="" autocomplete="off" novalidate>

web.php :

Route::post('developers/{dev_id?}/admins/{id}/edit', 'Admin\DeveloperAdminController@postEditDeveloperAdmin')->name('admin.developers.admins.edit.post')->where(['dev_id' => '[0-9]+', 'id' => '[0-9]+']);


via Chebli Mohamed

jeudi 25 juin 2020

Column not found cause i have diffirent coloumns name in my table

i have some issue when i wanna count row from relation table

i have 2 tables users and threads i wanna count all threads by id_user.

this in User model

public function thread(){
        return $this->hasMany('App\Thread');
    }
    
protected $primaryKey = "id";

this in Thread Model

protected $primaryKey = "id";

public function user(){

    return $this->belongsTo('App\User','id_users');
}

i try to count in my view like this


and this is my index method in controller

public function index()
{
    $users = Auth::user();
    $threads = Thread::orderBy('created_at','desc')
            ->get();

    return view('/home',compact('threads','users'));
}

i just put descending for showing data in my controller.

anyone have solution for this issue ???



via Chebli Mohamed

i am not able to find order through id in laravel

I am new to shopping cart. I am able to get all the data from order table on this page but i am not able to find single order by ID: This is my view page where i am sending the $id to the controller of the order. id)}}">Order# The whole code: '''

@foreach($orders as $order) @if($order->status == "CompletedOrders")

                    <div class="panel panel-default">
                        <div class="panel-body">
                            <ul class="list-group" >

                                <li class="list-group-item" style="background-color: #5C94ED">
                                    <a href=""><h1 style="color: #FBEB58">Order# </h1></a>
                                    <span class="badge" style="color: black; font-size: 16px">Name: </span>
                                    <br>
                                    <span class="badge" style="color: black; font-size: 16px">Phone: </span>
                                    <br>
                                    @foreach($order->cart->items as $item)
                                        <span class="badge" style="color: #FBEB58; font-size: 16px"> </span>
                                        <br>
                                        <span class="badge" style="color: #FBEB58; font-size: 16px">Price: $</span>
                                        <br>
                                    @endforeach
                                    <span class="badge" style="color: black; font-size: 16px">Instructions: </span>
                                    <br>
                                    <span class="badge" style="color: black; font-size: 16px">Time: </span>
                                    <br>
                            </ul>
                        </div>
                        <div class="panel-footer">
                            <strong style="color: #222D32; font-size: 18px">Total Price: $</strong>
                        </div>
                    </div>
                    
                    <input type="button" onclick="printDiv('printableArea')" value="print a div" />
                @endif
            @endforeach

''' This is my route

'''

Route::get('showcompleteorder/{id}','OrderController@showCompleteOrder')->name('showcompleteorder');

''' and this is my controller:

public function showCompleteOrder($id){
    $orders = Order::find($id);
    $orders->transform(function ($order, $key) {
        $order->cart = unserialize($order->cart);
        return $order;
    });
    return view('orders.showcompleteorders', ['orders' => $orders]);

}

but when i run this. it gives me a error of transform:

BadMethodCallException

Call to undefined method App\Order::transform() http://localhost:8000/showcompleteorder/2

This is my view where i am trying to get the order by id:

 @foreach($orders as $order)
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <ul class="list-group" >

                                <li class="list-group-item" style="background-color: #5C94ED">
                                    <h1 style="color: #FBEB58">Order# </h1>
                                    <span class="badge" style="color: black; font-size: 16px">Name: </span>
                                    <br>
                                    <span class="badge" style="color: black; font-size: 16px">Phone: </span>
                                    <br>
                                    @foreach($order->cart->items as $item)
                                        <span class="badge" style="color: #FBEB58; font-size: 16px"> </span>
                                        <br>
                                        <span class="badge" style="color: #FBEB58; font-size: 16px">Price: $</span>
                                        <br>
                                    @endforeach
                                    <span class="badge" style="color: black; font-size: 16px">Instructions: </span>
                                    <br>
                                    <span class="badge" style="color: black; font-size: 16px">Time: </span>
                                    <br>
                            </ul>
                        </div>
                        <div class="panel-footer">
                            <strong style="color: #222D32; font-size: 18px">Total Price: $</strong>
                        </div>
                    </div>

            @endforeach

Can Someone please help me



via Chebli Mohamed

Laravel E-commerce Restful API [closed]

i'm building a restful API For eCommerce App

and now i'm going to build Order Part. but i searched a lot and i didn't found anything about building Order Restful API.

So. is anyone knows anything about this?

Orders Table

id - Number - user_id - Created At - Updated At

Order Item Table

id - order_id - product_id

Product Table

title - description - price - Created At - Updated At


via Chebli Mohamed

why i do get an error on laravel-5 installation?

i getting this error on lavarel installation by composer-project,do you have any ideia how to solve?

Could not parse version constraint /var/www/html/my_blog1: Invalid version
string "/var/www/html/my_blog1"



via Chebli Mohamed

Url for API to login and get access token

I want to validate the email and password of someone connecting through an API.

The idea is that they login through POST to site.com/api/v1/token?email=foo@bar.com&password=foobar

I was reading that best practices should be to make a https://laravel.com/docs/7.x/validation#creating-form-requests to handle the validation, but I couldn't understand how to validate the $user, because when I created the new Class there wasn't any request there.

I'm not sure if I'm missing something. I was able to do it through the Controller just checking if the user exists and the password is valid.

The app would ping this URL with email/password, then get a Token as a response with the $user information and use this token to post/edit/delete other data



via Chebli Mohamed

Remove item from database in Laravel

I am beginner in Laravel and php. I use in my project (Laravel 7) this component: https://packagist.org/packages/kalnoy/nestedset

I need a function to delete the selected branch (record) along with the records "deep".

I try with this code:

public function destroy(Request $request, int $parentId, int $id)
    {
        $node = $this->model->where('id', $id)->get();

        $arrayToDelete = array();
        $traverse = function ($categories) use (&$traverse, &$arrayToDelete) {
            foreach ($categories as $category) {
                $arrayToDelete[] = $category->id;
                $traverse($category->children);
            }
        };
        $traverse($node);

        foreach ($arrayToDelete as $value) {
            $this->model->where('id',$value)->delete();
        }
        return redirect()->route('subcategory.index', ['id' => $id, 'parentId' => $parentId])->with('success', 'Rekord usunięty poprawnie');
    }

but I have error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (cms.products, CONSTRAINT products_category_id_foreign FOREIGN KEY (category_id) REFERENCES categories (id)) (SQL: delete from categories where id = 1)

My migration file:

Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category_name', 155);
            $table->string('description', 155)->nullable();
            $table->string('keywords', 155)->nullable();
            $table->longText('content')->nullable();
            $table->char('enable', 1)->default(0);
            $table->string('photo', 155)->nullable();
            $table->bigInteger('order')->default(0);
            $table->string('slug', 160)->nullable();
            NestedSet::columns($table);
            $table->engine = "InnoDB";
            $table->charset = 'utf8mb4';
            $table->collation = 'utf8mb4_unicode_ci';
        })

In manual: https://packagist.org/packages/kalnoy/nestedset

I found this:

Deleting nodes To delete a node:

$node->delete(); IMPORTANT! Any descendant that node has will also be deleted!

IMPORTANT! Nodes are required to be deleted as models, don't try do delete them using a query like so:

Category::where('id', '=', $id)->delete();

How should I change my code to. did the deletion work correctly?



via Chebli Mohamed

Laravel - Working with sessions between controllers

I need to show some values in all app, and sometimes I need to use these values between controllers. I was trying to use Session, but I maybe it is not the answer to that, because if I am not wrong, Laravel store the session data temporarily in memory and only after everything has been executed, will it dump the session data into storage (file, cookie, redis, whatever).

So for example, I have a controller like that:

class GiftController extends Controller
{
    public function dashboard(){
        $token = (Session::has('token')) ? Session::get('token') : NULL;
        if (is_null($token)){
           return view('test.erro', ['message' => 'no session!']);
        }else{
           return view('test.ok', ['message' => $token]);
        } 
    }


    public function setsession(){
          Session::put('token','xxxxxxxxxxxx');
          return redirect('test/dashboard');  
    }
}

In this case, if I do an echo on Session::get('token') into the setsession(), is showing the value, but when it goes to the dashboard(), the session shows nothing.

What I am doing wrong?
or What is the better Idea to use instead off session?

I am using the Laravel Framework 5.8.37



via Chebli Mohamed

Laravel Rest API - Get specific columns in json

i'm building Restful API Using Laravel

what i wanna to do is to get specific columns in JSON response instead on get all column

For example I've Product Table with these columns

title - price - description - status - created_at - updated at

and i just want to show title, price and description in JSON Response

So, any idea to do that?



via Chebli Mohamed

Gmail SMTP relay for sending emails in laravel

I am trying to send emails using Gmail SMTP relay using a laravel 5.6 application. I have a g-suite education account and using one of the emails of that account. Using simple SMTP settings it works fine however daily quota is only 2000 emails but for the relay, the quota is 10000 email.

the issue is the relay settings work sometimes and fail the other time.

here are the settings

MAIL_DRIVER=smtp

MAIL_HOST=smtp-relay.gmail.com

MAIL_PORT=587

MAIL_USERNAME=email@mydomain.com

MAIL_PASSWORD="an app password generated through the email settings"

MAIL_ENCRYPTION=TLS

i am getting the error "Expected response code 250 but got code "550", with a message "550-5.7.1 Invalid credentials for relay" and email sending fails...



via Chebli Mohamed

permission denied error with spatie/browsershot run

In my laravel 5 app I installed spatie/browsershot 3.37 and I got error on my server:

    The command "PATH=$PATH:/usr/local/bin NODE_PATH=`npm root -g` node '/var/www/html/the-box-booking/vendor/spatie/browsershot/src/../bin/browser.js' '{"url":"file:\/\/\/tmp\/1253868703-0501081001593084129\/index.html","action":"pdf","options":
{"path":"generate_profile_card_ybm8Xvk16rMUtQZXS0nUbZT9OdowS7upTFAU6iGr_tempfile.pdf","args":[],"viewport":{"width":800,"height":600},"displayHeaderFooter":false,"printBackground":true}}'" failed. Exit Code: 1(General error) Working directory: /var/www/html/the-box-booking/public Output: ================ Error Output: ================ ┌──────────────────────────────────────────────────────┐ │ npm update check failed │ │ Try running with sudo or get access │ │ to the local update config store via │ │ sudo chown -R $USER:$(id -gn $USER) /var/www/.config │ └──────────────────────────────────────────────────────┘ Error: 
EACCES: permission denied, open 'generate_profile_card_ybm8Xvk16rMUtQZXS0nUbZT9OdowS7upTFAU6iGr_tempfile.pdf' -- ASYNC -- at Page.<anonymous> (/usr/lib/node_modules/puppeteer/lib/helper.js:116:19) at getOutput (/var/www/html/the-box-booking/vendor/spatie/browsershot/bin/browser.js:35:40) at callChrome (/var/www/html/the-box-booking/vendor/spatie/browsershot/bin/browser.js:236:24) at processTicksAndRejections (internal/process/task_queues.js:97:5) { errno: -13, code: 'EACCES', syscall: 'open', path: 'generate_profile_card_ybm8Xvk16rMUtQZXS0nUbZT9OdowS7upTFAU6iGr_tempfile.pdf' }

where /var/www/html/the-box-booking - app root

and with code :

$save_to_file     = 'generate_profile_card_' . Session::getId() . '_' . $filename_to_save;


if (strtolower($option_output_file_format) == 'pdf') {
    Browsershot::html(htmlspecialchars_decode($pdf_content))
               ->showBackground()
               ->save($save_to_file);  // ERROR POINTING THIS LINE

looks like I lack some permittions. Which ?

Thanks!



via Chebli Mohamed

Complete the form with data from the Laravel database

I am beginner in php and Laravel. I have small problem with fill forms data from database. At the moment I am trying to complete my form with data from the database. The whole looks as follows:

@foreach($countertops as $value)
                                            @foreach ($value->features as $feature)
                                                @if ($feature->key == 'countertop_type')
                                                    @if ($feature->description == 4)
                                                        <input type="hidden" name="countertop[][id]" value="">
                                                        <div class="form-group row">
                                                            <div class="col-lg-4 col-md-4 col-sm-12 text-right pt-2">
                                                                <input type="checkbox"
                                                                       class="xxxxxx mr-2"
                                                                       name="countertop[][checkbox]"  @if(!empty($product) && (!empty($selectedCountertops)) && (!empty($selectedCountertops['countertop['.$value->id.'][checkbox]'])) && old('countertop['.$value->id."][checkbox]", $selectedCountertops['countertop['.$value->id.'][checkbox]'])) checked @endif
                                                                       value="1" >
                                                                <label></label>
                                                            </div>
                                                            <div class="col-lg-4 col-md-4 col-sm-5">
                                                                <input type="text"
                                                                       name="countertop[][min]"
                                                                       class="form-control currencyMask"
                                                                       value=""
                                                                       placeholder="Wpisz minimalną długość">
                                                            </div>
                                                            <div class="col-lg-4 col-md-4 col-sm-5">
                                                                <input type="text"
                                                                       name="countertop[][max]"
                                                                       class="form-control currencyMask"
                                                                       value=""
                                                                       placeholder="Wpisz maksymalną długość">
                                                            </div>
                                                        </div>
                                                    @endif
                                                @endif
                                            @endforeach
                                        @endforeach

The form display works correctly. The problem is only in:

  1. checking / unchecking the checkbox (checked when status == 1 or unchecked when == 0 or no exist)
  2. entering the maximum value in input (maxvalue)
  3. entering the minimum value in input (minvalue)

In controller I Have:

$selectedCountertops = $selectedCountertopsRepository->getSelectedItems($id);

Where getSelectedItems is:

....
public function getSelectedItems(int $id)
    {
        return $this->model->where('product_id', $id)->orderBy('id', 'ASC')->get();
    }
...

This return me:

Illuminate\Database\Eloquent\Collection {#1568 ▼
  #items: array:2 [▼
    0 => App\Models\SelectedCountertops {#1569 ▼
      #quarded: array:1 [▶]
      #fillable: array:5 [▶]
      #connection: "mysql"
      #table: "selected_countertops"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:8 [▼
        "id" => 1
        "countertops_id" => 8
        "product_id" => 10
        "status" => "1"
        "maxvalue" => "88.00"
        "minvalue" => "99.00"
        "created_at" => "2020-06-25 09:44:17"
        "updated_at" => "2020-06-25 09:44:17"
      ]
      #original: array:8 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => App\Models\SelectedCountertops {#1570 ▶}
  ]
}

This is my model:

class SelectedCountertops extends Model
{
    use ScopeActiveTrait;

    protected $quarded = ['id'];
    protected $fillable = ['product_id', 'status', 'maxvalue', 'minvalue', 'countertops_id'];

}

in blade file: $value->id is countertops_id from my model

How can I repair it?



via Chebli Mohamed

laravel 7 i cant access comment and user in pivote table of user_id and course id

i cant access in user dashboard to comment and user comment... i use this relations

public function review_teachers()
{return $this->belongsToMany(Course::class,'review_teaches','user_id','course_id')->withTimestamps();}

and review_teaches colomon has two row that name is course_id and user_id.

i defined in controller for get data

 $list_review = auth()->user()->review_teachers()->get();

i can access to course .for example if defined i can acceess to course title and it is ok

1 question: i want to call user->name but not work and review->comment but not work



via Chebli Mohamed

laravel blade data accessible in var_dump but not in template?

I have a blade template to which I pass an object in my controller. When I try to access the data in var_dump or outside HTML tags, I can see the content of the variable. However, I get a fatal error when loading the data inside html tags. gives me the article title but when I load my full template, it crashes at <title></title> it returns the follwing error : Undefined variable: title. Am I doing something wrong there ?



via Chebli Mohamed

How to check id of one table into another table using php variable?

I have two tables named

product(id,pname,price) 

and

add_to_card(id,pid,is_added)

The problem is that I want to check the product_id which is either exist or not on add_to_card table.

This is my controller:

public function add_to_card(){

   $pid = request('pid'); //I want to check this $pid on add_to_card table

}

I have no idea how to resolve this.. Please help me?



via Chebli Mohamed

Creating a package for validation. I want that my package can use be useable like-use Validation; Excel::alphanumeric()

Please help anyone if could get my vallidation in controller as use Excel; //this is our package Excel::load() // this is a function for load the excel

This is my Custom Rule

    namespace pebibits\validation\Rules;

use Illuminate\Contracts\Validation\Rule;

class Alphanumeric implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // dd("ok");
        
        return preg_match('/(^[\w-]*$)/',$value);
        
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'You can only have aplhabates.';
    }
}

This is my controller

    <?php

namespace pebibits\validation\Http\Controllers;
use pebibits\validation\Rules\Alphanumeric;
use pebibits\validation\Requests\Formvalidate;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class FormController extends Controller
{
    public function index()
    {
        return view('validation::form');
    }

    public function store(Formvalidate $request)
    {

       return $request->all();
    }
}

Please help anyone if could get my vallidation in controller as use Excel; //this is our package Excel::load() // this is a function for load the excel



via Chebli Mohamed

How to refresh highcharts (pie chart) data via ajax

I'm trying to auto-refresh my ajax queries in highcharts (pie chart). Basically i want my data to refresh every 5 seconds. But nothing appears in my screen. Trying to use events for highcharts, but I'm not sure if this is the right way to do it.

Here's a snippet of my JS:

const leadstatus_peryear_title = $('#valLeadPerYear').val();
    var leadbyyear_chart;
    function requestLeadStatusByYear(){
        $.ajax({
            url: '/sample/dashboard/query',
            method: 'get',
            dataType: 'json',
            success:function(result){
                var resultsArr = [];
            $.each(result, function(index, element) {
                    resultsArr.push({
                        status: index,
                        status_count: parseFloat(element)
                    });
                });

                var data = [];
                $.each(resultsArr, function(index, element) {
                    data.push({
                        name: element.status,
                        y: element.status_count
                    });
                });
                leadbyyear_chart.series[0].data = data;
                // call it again after one second
                setTimeout(requestLeadStatusByYear, 1000);
            },
            cache: false
        });
    }

    document.addEventListener('DOMContentLoaded', function() {
        leadbyyear_chart = Highcharts.chart('leadsPerYear', {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie',
                events: {
                    load: requestLeadStatusByYear
                }
            },
            title: {
                text: leadstatus_peryear_title
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            accessibility: {
                point: {
                    valueSuffix: '%'
                }
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                    }
                }
            },
            series: [{
                name: 'Number of Leads in Percent',
                colorByPoint: true,
                animation: false,
                data: []
            }]
        });
    });

Appreciate your help :)



via Chebli Mohamed

Undefined variable in blade file

I am beginner in Laravel and web development. I have this code in blade file:

@foreach($plates as $value)
                                            @if ($value->type == 1)
                                                <div class="form-group row">
                                                    <div class="col-lg-4 col-md-4 col-sm-12 text-right pt-2">
                                                        <input type="checkbox"
                                                               class="xxxxxx mr-2"
                                                               name="plate-ch-"  @if(old('plate-ch-'.$value->id, $selectedProductFeatures['plate-ch-'.$value->id])) checked @endif
                                                               value="1" >
                                                        <label></label>
                                                    </div>
                                                   
                                                </div>
                                            @endif
                                        @endforeach

I have error:

Undefined variable: selectedProductFeatures (View: /Applications/XAMPP/xamppfiles/htdocs/roelle/resources/views/admin/products/view.blade.php)

This is wrong line: name="countertop-ch-" @if(old('countertop-ch-'.$value->id, $selectedProductFeatures['countertop-ch-'.$value->id])) checked @endif

I have a universal template for adding and editing a product.

How can I repair it?



via Chebli Mohamed

Why Observer's Saved method not working for while update the record in laravel 5.3

I have project in laravel 5.3 and i am using Observer for activity log of user, for that i have created one obeserver with saved() and deleted() method.

The saved() method is working fine for new record, while update the record saved() is not getting call nor updated() method.

I also try with deleted() method, that is also not getting call, here below is my code, please help.


    public function __construct()
    {
        // echo "dsd"; die();
    }

    public function saved($user)
    {
        if ($user->wasRecentlyCreated == true) {
            // Data was just created
            $action = 'created';
        } else {
            // Data was updated
            $action = 'updated';
        }
        
        UserAction::create([
            'user_id'      => Auth::user()->id,
            'action'       => $action,
            'action_model' => $user->getTable(),
            'action_id'    => $user->id
        ]);
    }

    public function deleting($user)
    {
        dd($user); 
    }
}



public static function boot() { 
        parent::boot(); 
        parent::observe(new \App\Observers\UserObserver); 
    }


via Chebli Mohamed

mercredi 24 juin 2020

why is not find user email to database?

public function create(Request $request){

$this->validate($request, [
 'email' => 'required|email',

]);

   $user = user::where('email',$request->email)->first();      
     if ($user)
   return response()->json([
       'message' => 'We can not find a user with that e-mail address.'
   ], 404);
   
   
   $passwordReset = PasswordReset::updateOrCreate(
  
   [
        //'email' =>$user->email,
        'email'=>$request->email,
        'token' => str_random(60)
    ]
   
);

if ($user && $passwordReset)
$user->notify(
    new PasswordResetRequest($passwordReset->token)
);       
 return response()->json([
'message' => 'We have e-mailed your password reset link!'

]);

}



via Chebli Mohamed

Permission problems with Laravel's storage directory on CentOS 7. Changing permissions and ownship with chmod and chown does not solve it

I figured this out myself while I was revising my question, but I'm going to post my original question anyway with the solution in case it helps anyone else.

The solution has nothing to do with symbolic links or Deployer, but I'm going to leave my question as is in case someone came to the same problem in a similar way.


I'm trying to set up a Laravel 5.8 deployment using Deployer on a CentOS 7 server.

The deployment is successful. The storage folder is set as a shared directory in my deploy.php file, so what it does it sets up the storage folder as a persistent shared folder between releases. It does this by creating a symbolic link to a shared storage folder for the releases.

There is a folder for the current release at /var/www/test-laravel/current, which is actually a symbolic link to the folder with the most recent release (in this case /var/www/test-laravel/releases/18). Inside that folder the storage folder is actually a symbolic link to /var/www/test-laravel/shared/storage.

I was getting the following error,

The stream or file "/var/www/test-laravel/releases/18/storage/logs/laravel-2020-06-25.log" could not be opened: failed to open stream: Permission denied

After trying a few variations of permissions/owners/groups, out of frustration I manually ran chmod -R 777 and chown -R apache.apache on not just the original storage folder but on all of the symlink folders as well.

This hasn't changed anything at all. I'm still getting the same error.

I don't think this should make a difference, but just for good measure I've run php artisan cache:clear, php artisan view:clear and php artisan config:clear.



via Chebli Mohamed

Laravel remove pending migration execution

I have two Laravel apps that use the same database. I moved migrations from app 1 to app 2. Now I want to remove the pending migrations from app 2 due to that I moved the migrations files to it and tables exists in database.

Is any way to remove them from pending execution when php artisan migrate is executed?

Regards



via Chebli Mohamed

laravel eger loading not working properly when i use limit or take in whereIn

helllo my code is

$all_5_post = wp_terms::with(['wp_posts' => function ($query) {
                                      $query->orderBy('id', 'desc')->take(5);
                                }])->whereIn('id',[3,4,6,9])->get();

getting relationship data in 3 id but 4,6,9 relationship data getting empty but when i only use WHERE elequent and doing multiple query for same 3,4,6,9 id it showing 5 relationship table data in each what i have to do now i need a solution.



via Chebli Mohamed

how to store the select value of select box for search

Dear Stackoverflow team! i want to make the search condition with form like picture attachment. i want to store the select box value after form submit to search with multiple condition. so could the the team help make solution for it. below is my model filter condition, it's laravel code

public function scopeFilterInProfile($query, Request $request)
{
    $query = Property::where('user_id',auth()->user()->id)
                    ->published()
                    ->expired();
    if ($request->input('category')) {
        $query->where('parent_id', $request->input('category'));
    }
    if ($request->input('location')) {
        $query->where('province_id', '=', $request->input('location'));
    }
    if ($request->input('search')) {
        $query->where('title', 'LIKE', '%'.$request->input('search').'%');
    }
    if ($request->input('from_price') && $request->input('to_price')) {
        $query->whereBetween('price', [$request->input('from_price'),$request->input('to_price')]);
}
    if ($request->input('sort')) {
        switch ($request->input('sort')){
            case 'posted_date_desc':
                $query->orderBy('created_at', 'DESC');
                    break;
            case 'posted_date_asc':
                $query->orderBy('created_at', 'ASC');
                    break;
            case 'renew_date_desc':
                $query->orderBy('renew_date', 'DESC');
                    break;
            case 'renew_date_asc':
                $query->orderBy('renew_date', 'ASC');
                    break;
            case 'price_desc':
                    $query->orderBy('price', 'DESC');
                    break;
            case 'price_asc':
                $query->orderBy('price', 'ASC');
                    break;
            default:
                $query->orderBy('posted_date_desc', 'DESC');
        }
    }
    return $query;
}

myform search picture



via Chebli Mohamed

I got symfony/translation errors installing laravel 5 on remote server

Uploading my laravel 5 app on ubuntu under Digital Ocean server I got error in the browser:

Declaration of Symfony\Component\Translation\TranslatorInterface::setLocale($locale) must be compatible with Symfony\Contracts\Translation\LocaleAwareInterface::setLocale(string $locale)

Googling for decision I found that the error could need symfony/translation installation and I tried to install it locally on my kubuntu 18 and got error :

$ composer require symfony/translation                                     
Using version ^5.1 for symfony/translation
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install symfony/translation v5.1.2
    - Conclusion: don't install symfony/translation v5.1.1
    - Conclusion: don't install symfony/translation v5.1.0
    - Conclusion: don't install symfony/translation v5.1.0-RC2
    - Conclusion: don't install symfony/translation v5.1.0-RC1
    - Conclusion: don't install symfony/translation v5.1.0-BETA1
    - Conclusion: don't install symfony/translation 5.2.x-dev
    - symfony/translation 5.1.x-dev conflicts with symfony/http-kernel[v4.4.9].
    - symfony/translation 5.1.x-dev conflicts with symfony/http-kernel[v4.4.9].
    - Installation request for symfony/translation ^5.1 -> satisfiable by symfony/translation[5.1.x-dev, 5.2.x-dev, v5.1.0, v5.1.0-BETA1, v5.1.0-RC1, v5.1.0-RC2, v5.1.1, v5.1.2].
    - Installation request for symfony/http-kernel (locked at v4.4.9) -> satisfiable by symfony/http-kernel[v4.4.9].

My local composer.json :

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "arrilot/laravel-widgets": "^3.13",
        "doctrine/dbal": "^2.9",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "^1.0",
        "mews/purifier": "^2.1",
        "phpoffice/phpspreadsheet": "^1.6",
        "proengsoft/laravel-jsvalidation": ">2.2.0",
        "s-ichikawa/laravel-sendgrid-driver": "^2.0",
        "spatie/browsershot": "^3.37",
        "spipu/html2pdf": "^5.2",
        "yajra/laravel-datatables-oracle": "~8.0"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

How this can be salved ? Thanks!



via Chebli Mohamed

Laravel Api and Web Authentication At Same Time

i'm building cross-platform app so i have website and mobile app. also I've Authentication part for both website and app.

and i'm using Laravel As backend. For auth i found something called "Auth Guards" and there are two default Auth guard in Laravel, one for web and other for API.

But i'm a bit confused cause i found that you can't use both Auth Guards at the same time.

So, is there any way to build authentication system based in one Database Table For Website an Mobile.

NOTE i need any solution except Firebase Auth



via Chebli Mohamed

Azure AD identity provider with laravel 5.2

Can I implement azure AD as a identity provider with my laravel version 5.2? If yes can anyone give me link or suggest something about it? you can also suggest me another identity provider which will be compatible with laravel 5.2.



via Chebli Mohamed

Search value in array in Laravel Blade

I am beginner in Laravel.

I have array in variable $selectedProductFeatures:

array:9 [▼
  0 => array:9 [▼
    "id" => 9
    "product_id" => 3
    "feature_id" => 1
    "key" => "price60"
    "description" => "60"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  1 => array:9 [▼
    "id" => 10
    "product_id" => 3
    "feature_id" => 1
    "key" => "price60_promo"
    "description" => "65"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  2 => array:9 [▼
    "id" => 11
    "product_id" => 3
    "feature_id" => 1
    "key" => "price90"
    "description" => "90"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  3 => array:9 [▼
    "id" => 12
    "product_id" => 3
    "feature_id" => 1
    "key" => "price90_promo"
    "description" => "95"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  4 => array:9 [▼
    "id" => 13
    "product_id" => 3
    "feature_id" => 1
    "key" => "countertop_length"
    "description" => "1000.00"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  5 => array:9 [▼
    "id" => 14
    "product_id" => 3
    "feature_id" => 1
    "key" => "countertop_type"
    "description" => "4"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  6 => array:9 [▼
    "id" => 15
    "product_id" => 3
    "feature_id" => 1
    "key" => "maintenance"
    "description" => "<p>konserwacja</p>"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  7 => array:9 [▼
    "id" => 16
    "product_id" => 3
    "feature_id" => 1
    "key" => "other_title"
    "description" => "tytuł inny"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
  8 => array:9 [▼
    "id" => 17
    "product_id" => 3
    "feature_id" => 1
    "key" => "other_description"
    "description" => "<p>opis inny</p>"
    "maxvalue" => "0.00"
    "minvalue" => "0.00"
    "created_at" => "2020-06-24T08:27:35.000000Z"
    "updated_at" => "2020-06-24T08:27:35.000000Z"
  ]
]

return view('admin.products.view', ['selectedProductFeatures' =>$selectedProductFeatures->toArray(), 'productTypes' => $productTypeRepository->allEnables('name', $orderBy = 'asc', $with = []), 'fileCount' => 5, 'fileFolder' => 'products', 'fileId' => $id, 'product' => $this->model->findOrFail($id), 'categories' => $categories, 'taxVat' => $vatRepository->allEnables('value', 'asc'), 'page_title' => 'Produkty', 'page_breadcrumbs' => [['page' => route('product.index'), 'title' => 'Produkty'], ['page' => '#', 'title' => 'Edytuj produkt']]]);

My blade file:

<input type="text" name="price60" value="">
<input type="text" name="price90" value="">

In price60 I need show value from array (array is dynamic).

"key" => "price60" -- this is name input "description" => "60" - this value to show.

In result I need:

For "key" => "price90" and "description" => "90" in input I need show:

<input type="text" name="price90" value="90">

How can I make it?



via Chebli Mohamed