Laravel Attempt to read property "produits" on null - php

whene i do the login action it return the error above where there is no user all work good
$currentTime = date("Y-m-d");
if(Auth::check()){
$user = Auth::user();
$favorie = $user->favorie;
$favprds = $favorie->produits;
}else{
$favprds = [];
}
this is my blade i believe that there is no probleme with blade
#for ( $i = 0; $i < count($favprds) ;$i++)
#if ($favprds[$i]->id == $pro->id)
<div class="tinv-wishlist-clear">
<a style="color:red;" href="{{ url('deleteFavorie/'.$pro->id) }}"><i class="fa fa-heart"></i></a>
</div>
#break
#elseif($favprds[$i]->id != $pro->id && $i == count($favprds)-1)
<div class="tinv-wishlist-clear">
<i class="klbth-icon-heart-1"></i>
</div>
#endif
#endfor
#if(count($favprds) == 0)
<div class="tinv-wishlist-clear">
<a style="color:#7f8c8d" href="{{ url('add-to-favorie/'.$pro->id) }}"><i class="klbth-icon-heart-1"></i></a>
</div>
#endif

it seems that the way i access the products is the wrong way thought i still have to test if the there's a probleme with adding to the favorite product
$currentTime = date("Y-m-d");
if ($favorie = auth()->user()->favorie ?? false) {
$favprds = $favorie->produits;
} else {
$favprds = [];
}

Related

Reset alpine component to initial state

I'm starting with Alpine js and I use a component with plus and minus buttons to add or remove items, however this is used in a modal that when invoked brings a specific product, the problem is that when closing the modal and opening it again with another product the component values ​​do not update, is there a way to reset to the initial state?
<div wire:model.defer='{{ $wiremodel }}'
class="input-group input-group-sm {{$size == 'l' ? 'input-group-lg': ''}} {{$size == 's' ? 'input-group-sm': ''}}"
x-data="{ count: {{ $min }}, max:{{ $max }}, min:{{ $min }}, price:{{ $price }},
increment(){
var incre;
if(this.max == 0){
incre = true;
this.count ++;
}else{
this.count == this.max ? incre = false : incre = true;
this.count == this.max ? this.count : this.count++;
}
if(incre){
var oldprice;
var newprice;
oldprice = $('#price_product_button').attr('data-price');
newprice = parseFloat(this.price) + parseFloat(oldprice);
$('#price_product_button').attr('data-price', newprice);
$('#price_product_button').html(newprice.toLocaleString('pt-BR', { style: 'currency' , currency:'BRL'}));
}
},
decrement(){
var decre;
this.count == this.min ? decre = false : decre = true;
this.count == this.min ? this.count : this.count--;
console.log(this.count);
if(decre){
var oldprice;
var newprice;
oldprice = $('#price_product_button').attr('data-price');
newprice = parseFloat(oldprice) - parseFloat(this.price) ;
$('#price_product_button').attr('data-price', newprice);
$('#price_product_button').html(newprice.toLocaleString('pt-BR', { style: 'currency' , currency:'BRL'}));
}
}
}">
<div class="input-group-prepend">
<button #click="decrement() ; $dispatch('input', count)" class="btn btn-outline-light bg-white text-danger" data-price="">
<i class="fas fa-minus"></i>
</button>
</div>
<input readonly x-model.number="count" class="form-control border-0 text-center input-btn-add-remove"
placeholder="{{ $min }}" />
<div class="input-group-append">
<button #click="increment() ; $dispatch('input', count)" class="btn btn-outline-light bg-white text-danger">
<i class="fas fa-plus"></i>
</button>
</div>
</div>```
If the x-data object of a component contains an init() method, it will be called automatically. For example:
<div x-data="{
init() {
this.count = {{ $min }};
this.max = {{ $max }};
this.min = {{ $min }};
this.price = {{ $price }};
}
}">
...
</div>
You can use that fact for your advantage and everytime the modal opens, the init method can be called to reset the values to its original state. Also it will be called automatically on the first init.

Handle a list of files over laravel CRUD

I'm working on a form where you have to enter all information you need and at the end, on save all information will be saved at the same times. The form have a list of images where you can add, change and delete pictures.
The way it was made is that all inputs refer to the name carousels[]. Adding the file is alright, the problem is that this way I have no way to identify in backend which file I have to delete or change.
I'm wondering if any Laravel master know a better way to handle a list of files over a form the way a need it to work. So I would be able to add new images, replace an old image by a new one and/or delete a specific image.
There are the pieces of code I'm working with.
Frontend:
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="carrousels[]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Backend
public function update(UpdateRequest $request)
{
try {
$id = $request->id;
$carrouselFolder = config('constants.DEFAULT.UPLOAD_FOLDERS.CARROUSEL');
$carrousels = [];
Log::debug($request->carrousels);
if ($request->carrousels) {
foreach ($request->carrousels as $image) {
if (!empty($image)) {
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
}
return redirect()->to(route('...'))
->with('toastSuccess', '...');
} catch (\Exception $e) {
return redirect()->back()->with('toastError', $e->getMessage());
}
}
send another parameter with old carousel, retrive it in controller then if both not empty, delete the old image . you can try this
View code
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="text" name="oldcarrousels[{{$i}}]" value="{{ !empty($carrousel[$i]) ?$carrousel[$i] :'' }}">
<input type="file" name="carrousels[{{$i}}]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Controller code
foreach ($request->carrousels as $in=>$image) {
if (!empty($image)) {
if (!empty($request->oldcarrousels[$in]) || $request->oldcarrousels[$in]!='') {
//image deleting code here
}
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}

How to update and delete comments from database?

First of all, I want to save comments after editing.I'm able to save the other features, but now I need to save comments too because they are in other table.
Here is my code for comments:
#foreach($event_comm as $comm)
<div class="row">
<div class="col-md-4">
<label class="label" style="color: black">Comment by {{$comm->user->username}}</label>
<label class="input">
{{ Form::text('comments', $comm->comments) }}
</label>
#endforeach
My update function
public function update($type, $id)
{
/* print_r(Input::all()); die; */
if($type == "Opinion")
{
$article = \App\Opinion::find($id);
$article->subject = Request::input('subject');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->opinion = Request::input('opinion');
$article->update();
}
if($type == "Event")
{
$event_comm = EventComment::where('event_id', $id)->get();
$article = \App\Event::find($id);
$article->subject = Request::input('subject');
$event_comm->comments = Request::input('comments');
$article->public = Request::input('public');
$article->category_id = Request::input('category_id');
$article->website = Request::input('website');
$article->email = Request::input('email');
$article->telephone = Request::input('telephone');
$article->information = Request::input('information');
$article->update();
}
return redirect(URL::previous())
->with(compact('event_comm'));
}
I've already tried to add $event_comm->comments = Request::input('comments'); but doesn't work.
2.Second problem.I want to also delete comments from database with a button or something like that.I found a route but I'm not sure if works.I need to know how to add this into my file?With a button ?
My route
Route::get('admin/article/deleteComment/{type}/{id}',['as' => 'deleteComment', 'uses' => 'ArticleController#deleteComment']);
public function deleteComment($type, $id)
{
if($type == "Event")
{
$comment = \App\EventComment::find($id);
}
if($type == "Opinion")
{
$comment = \App\OpinionComment::find($id);
}
$comment->delete();
return redirect('admin/comments');
}
Button:
<button href="{{ url('deleteComment',$type, $id) }}" role="button" class="btn btn-xs btn-danger" onclick="return confirm('Are you sure you want to delete this comment?');">Delete <i class="fa fa-trash"></i></button>

How to Fix Undefined Variable id error in laravel 5.7

M working on a solution where by i need to pass data from controller to view, Based on the id.
I've tested each variable one by one for see if there is actual data contained in those variables.
one-by-one produces all the values required and as soon as i comment out the var_dumps(). Throws an Undefined index error.
Please See code below:
View
<td>
<a href="view-campaign/{{$item->id}}" class="btn btn-success mb-2"
data-toggle="tooltip" title="view campaign">
<i class="fa fa-eye"></i>
</a>
</td>
Controller
public function viewCampaign($id){
//return var_dump($id);
$img = null;
//firebase configs and send to firebase
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/serviceKey.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->withDatabaseUri('https://projectName.firebaseio.com/')
->create();
$database = $firebase->getDatabase();
$ref = $database->getReference('CampaignCollection')->getValue();
foreach($ref as $key){
$item = $key['id'];
//return var_dump($item);
$poster = $key['Poster'];
//return var_dump($poster);
if($item = $id){
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
return view('view-campaign')->with('img',$img);
}
Route
Route::get('view-campaign/{id}','CampaignController#viewCampaign');
View::Results
#extends('layouts.layout')
#section('content')
<div class="col-md-12">
<div class="col-md-12 panel">
<div class="col-md-12 panel-heading">
<h4>View Campaign:</h4>
</div>
<div id="imgContainer" class="col-md-12 panel-body">
<i class="fa fa-arrow-circle-left"></i>
#if(isset($img))
<div align="center">
<img src="{{($img)}}" />
</div>
#else
no data
#endif
</div>
</div>
</div>
#endsection
Goal is to get the base64 code to pass to the view.
Try replacing your foreach with the following code:
foreach($ref as $k1 => $key){
$item = $key->id; //change over here
//return var_dump($item);
$poster = $key->Poster; //change over here
//return var_dump($poster);
if($item == $id){ //change over here
//return '1';
$img = $poster;
//return var_dump($poster);
}else{
return '0';
}
}
I reckon, you would also have to update the function signature to look something like following:
public function viewCampaign(Request $request , $id){
//your code
}

How to loop through this array in Laravel?

I am working on a web application using laravel 5.3, I got one problem.
I want to loop through this array.
What I tried is:
Controller:
public function postSearch(Request $request)
{
$categoryid = $request->category_id;
$locationid = $request->location_id;
$category = Category::where('id', $categoryid)->first();
$cities = Location::where('id', $locationid)->pluck('city');
$cityname = $cities[0];
$alllocations = [];
$ratecards = [];
$locations = [];
$father = [];
$i = 0;
$filteredlocations = $category->locations->where('city', $cityname)->all();
foreach($filteredlocations as $location){
$alllocations[$i] = $location->getaddetails;
$ratecards[$i] = $location->ratecard;
$i++;
}
$father[0] = $alllocations;
$father[1] = $ratecards;
return view('ads', compact('father'));
}
View is here:
#foreach($father as $key => $f)
#foreach($f as $key => $arr)
#if (isset($arr->adName))
<div class="post">
{{Html::image($arr->path,'Ad Picture',array('class' => 'ad-image'))}}
<h2 class="post-title">{{ $arr->adName }}</h2>
<p class="description">{{ $arr->description }} </p>
<div class="post-footer">
<span class="categories">
<ul class="cats">
<li class="btn btn-default">Price :
{{ $f[$key]->monthly_rate }}
</li>
<li class="btn btn-default">Status:
#if($arr->status == 1)
<p>Active</p>
#else
<p>Not-Active</p>
#endif
</li>
<li>view details</li>
</ul>
</span>
</div>
</div>
#endif
#endforeach
#endforeach
Problem:
Okay problem is when I try to get {{ $f[$key]->monthly_rate }} which is the 2nd array i.e RateCards I get nothing. I want to get the Rate Card array and from that array mothly_rate which is a field in there.
Thanks
PS : {{ $f[$key]->monthly_rate }} this return nothings in view.
The problem is that $f[$key] is an array of two objects.
That means that the properties youre looking for are inside each of those items, like this:
$f[$key][0]->monthly_rate
$f[$key][1]->monthly_rate
You will have to loop those objects to get their properties values.

Categories