Increase Quantity If Product don't Exists yet In Cart - php

i want to be able to increase and decrease quantity item before submiting data to the cart
this is my increase and decrese methods they work fine already tested
public function decrease($id)
{
$user = Auth::user();
$panier = $user->panier;
foreach ($panier->produits as $produit) {
if ($produit->id == $id) {
$qt = $produit->pivot->quantite;
$qt--;
if ($qt == 0) {
$panier->produits()->detach($produit->id);
} else {
$panier->produits()->updateExistingPivot($produit->id, ['quantite' => $qt]);
}
}
}
return redirect()->back();
}
public function increase($id)
{
$user = Auth::user();
$panier = $user->panier;
foreach ($panier->produits as $produit) {
if ($produit->id == $id) {
$qt = $produit->pivot->quantite;
$qt++;
$panier->produits()->updateExistingPivot($produit->id, ['quantite' => $qt]);
}
}
return redirect()->back();
}
the probelem is in my blade i remove the comment from the input value it return this error Attempt to read property "quatity" on null i don't know what to do this is the third day already
<div class="quantity">
<a href="{{route('decrQtePanier',['id'=> $prod->id])}}" class="quantity-button minus">
<i class="klbth-icon-minus"></i>
</a>
<input value="{{--$prod->pivot->quatity--}}" name="cart[15945][qty]" type="text" id="quantity_61a9f089c4906" class="input-text qty text" step="1" min="1" max="11" size="4" placeholder="" inputmode="numeric" />
<a href="{{route('incrQtePanier',['id'=> $prod->id])}}" class="quantity-button plus">
<i class="klbth-icon-plus"></i>
</a>
</div>
<a style="text-decoration:none; " href="{{ url('add-to-cart/'.$prod->id) }}">
<button style="border-radius: 50px; padding:0 20px; margin-left:40px" type="submit" name="add-to-cart" value="352" class="single_add_to_cart_button button alt">
Ajouter
</button>
</a>
this is my cart module
use HasFactory;
protected $fillable = ['user_id'];
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function produits()
{
return $this->belongsToMany('App\Models\Produit','produits_paniers')
->withPivot('quantite');
}
and this is my product module
use HasFactory;
protected $fillable = [
'nom', 'prix', 'prixpromo', 'detals', 'image','categorie_id','user_id'
];
public function favories()
{
return $this->belongsToMany('App\Models\Favorie');
}
public function paniers()
{
return $this->belongsToMany('App\Models\Panier');
}
public function commandes()
{
return $this->belongsToMany('App\Models\Commande');
}
public function categories()
{
return $this->belongsTo('App\Models\Categorie','categorie_id');
}
this is my routes this operation i'm using is in the detail route i'm newbe and i'm really stuck in here
Route::get('/detail/{id}', 'App\Http\Controllers\HomePageController#product_detail');
Route::get('/decreasePanier/{id}', 'App\Http\Controllers\PanierController#decrease')->middleware('auth')->name("decrQtePanier");
Route::get('/increasePanier/{id}', 'App\Http\Controllers\PanierController#increase')->middleware('auth')->name("incrQtePanier");

Related

ArgumentCountError Too few arguments to function App\Http\Controllers\Shop\CartController::addToCart()

So this function is supposed to add the product into a cart, but i've been getting the error
Too few arguments to function
App\Http\Controllers\Shop\CartController::addToCart(), 0 passed in
C:\xampp\htdocs\nerdS\vendor\laravel\framework\src\Illuminate\Routing\Controller.php
on line 54 and exactly 1 expected
I tried changing key words here and there on my controller, but nothing seems to do it. This is the the controller:
<?php
namespace App\Http\Controllers\Shop;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
Use App\Models\Product;
Use App\Models\Order;
class CartController extends Controller {
public function placeOrder() {
if(session('id')){
if(\Cart::count()){
\App\Models\Order::store();
return redirect('shop')->with('status', 'Thank you for buying!');
}
return redirect('cart');
}
session(['place-order-process' => true]);
return redirect('login')->with('status', 'To complete your order, please log in. Not a member yet? Join the club! ');
}
public function deleteCart() {
\Cart::destroy();
return redirect('shop')->with('status', 'The cart is now empty.');
}
public function deleteItem($rowId) {
\Cart::remove($rowId);
return redirect('cart')->with('status', 'The item was deleted.');
}
public function updateCart(Request $request){
\Cart::update($request->rowId, $request->quantity);
$data = [
'cart_count' =>\Cart::count(),
'cart_total' => \Cart::total(),
'product_total' => \Cart::get($request->rowId)->total(),
];
return json_encode($data);
}
public function displayCart() {
\Cart::setGlobalTax(0);
$data['items'] = \Cart::content();
$data['total'] = \Cart::total();
return view('cart.cart', $data);
}
public function addToCartByQty (Request $request){
\App\Models\Product::addToCart($request->id, (int) $request->quantity);
return \Cart::count();
}
public function addToCart ($id){
\App\Models\Product::addToCart($id);
return \Cart::count();
}
}
My model for products:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Product extends Model {
public function category() {
return $this->belongsTo('App\Models\Category');
}
public static function deleteProduct($id){
$product = self::findOrFail($id);
Storage::disk('public')->delete($product->image);
self::destroy($id);
}
public static function editProduct($request){
$product = self::findOrFail($request->product);
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
if ($request->image){
Storage::disk('public')->delete($product->image);
$product->image = $request->image->store('images/products', 'public');
}
$product->save();
}
public static function getProductById($id){
return self::finOrFail($id);
}
public static function store($request){
$product = new self();
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
$product->image = $request->image->store('images/products', 'public');
$product->save();
}
public static function getAll(){
return self::orderBy('slug')->get();
}
public static function addToCart($id, $qty = 1){
$product = self::findOrFail($id);
\Cart::add([
'id' => $product->id,
'name' => $product->name,
'qty' => $qty,
'price' => $product->price,
'weight' => 0
]);
}
public static function getProduct($cat, $pro){
$product = self::where('slug', $pro)->firstOrFail();
$product_cat = $product->category->slug;
//retun ($product_cat === $cat) ? $product_cat: false;
abort_if($product_cat !== $cat, 404);
return $product;
}
//use HasFactory;
}
The page view:
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart')}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
and my route:
Route::get('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
You need to pass the $product->id in the form action's url(). That route parameter needs to be there so that it is received in the addToCart method in controller
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart/' . $product->id)}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
And you have declared your route as get instead of post. Following restful conventions your route should be declared as a post route
Route::post('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
There is a mismatch in your route (Route::get('add-to-cart/{product_id}) and the parameter passed in your function addToCart ($id)
Had u provide product_id in route (add-to-cart/{product_id})?
Since you are using a GET route vs POST, you have to change your form method from POST to GET and also pass the id in the action url -
<form id="add-to-cart" method="get" action="{{url('add-to-cart/' . $product->id)}}">
Change your definition of addToCart method in CartController as following.
public function addToCart (Request $request, $id)
{
\App\Models\Product::addToCart($id);
return \Cart::count();
}

How to set limit to 4 users?

I have this section on my website: [1]: https://imgur.com/a/xJjb1ww "section"
I want to limit this photos to show max. 4 contacts, because if I have more, it looks bad.How can I add to this a max. limit to show?Sorry for so much code but I don't know exactly where is my function.Thank you.
Here is my view:
<!-- Tabs Widget -->
<div class="tab-content" style="padding: 8px !important">
<?php $count_user = 0; ?>
#foreach($user->contact as $contact)
<div id="contact<?php echo $count_user++; ?>" class="tab-pane magazine-sb-categories <?php if($count_user == 1){ echo "active"; } ?>">
<div class="row team-v1">
<ul class="list-unstyled col-xs-12" style="margin-bottom: -10px">
<li><h3 style="margin-top: 5px !important;text-transform: none; " >
#if($contact->role[0]->slug == "individuals")
<i style="font-size: 13px;" class="icon-user"></i>
#elseif($contact->role[0]->slug =='organizations')
<i style="font-size: 13px;" class="icon-hotel-restaurant-172 u-line-icon-pro fa- fa-lg"></i>
#endif
<a style="font-size: 14px" href="{{ url('') }}/{{ $contact->username }}">{{ $contact->username }}</a></h3>
<p>
<strong><i class="icon-real-estate-020 u-line-icon-pro"></i> : </strong><a>{{ $contact->country->country }}</a><br>
<strong><i class="icon-screen-tablet fa-" aria-hidden="true"></i> : </strong><a>{{ $contact->industry->industry }}</a><br>
#if($contact->role[0]->slug == "individuals")
#foreach($contact->career_path as $career_path)
<i style="font-size: 13px" class="icon-speedometer"></i> : {{ $career_path->functions->function }}
#break;
#endforeach
#elseif($contact->role[0]->slug =='organizations')
<i style="font-size: 13px" class="icon-frame fa-"></i> : {{ $user->organization_type->organization_type }}<br>
#endif
</p>
</ul>
</div>
#endforeach
Here is my User.php:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class User extends Authenticatable
{
use SoftDeletes;
/**
* 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',
// ];
public function comment()
{
return $this->hasMany('App\Comment');
}
public function country()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\Country','country_id','id');
}
public function organization_type()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\OrganizationType');
}
public function industry()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\Industry');
}
public function career_path()
{
return $this->hasMany('App\CareerPath');
}
public function education()
{
return $this->hasMany('App\Education');
}
public function about()
{
return $this->hasOne('App\About');
}
public function portfolio()
{
return $this->hasOne('App\Portfolio');
}
public function language_skills_selected()
{
return $this->belongsToMany('App\LanguageSkill','language_skills_selected','user_id','language_skills');
}
public function offices_branch()
{
return $this->hasMany('App\OfficesBranch');
}
public function my_alert()
{
return $this->hasOne('App\MyAlert');
}
public function privancy_setting()
{
return $this->hasOne('App\PrivancySetting');
}
public function event()
{
return $this->hasMany('App\Event');
}
public function news()
{
return $this->hasMany('App\News');
}
public function opinion()
{
return $this->hasMany('App\Opinion');
}
public function career_solution()
{
return $this->hasMany('App\CareerSolution');
}
public function contact()
{
return $this->belongsToMany('App\User','contacts','contact_id','user_id');
}
public function user()
{
return $this->belongsToMany('App\User','contacts','user_id','contact_id');
}
}
public function contact()
{
return $this->belongsToMany('App\User','contacts','contact_id','user_id')->limit(4);
}
This should be done in User.php.
If you have a relationship set up for $user->contact (i.e. hasMany), you should be able to call it like this in your loop in your blade file:
$limitedContacts = $user->contact->limit(4);
#foreach($limitedContacts as $contact)
....
#endforeach

I want to display username of comment's owner, however, comments table has user_id only

After I send the variable that contains the comments to the view, I can only display the user id. This is why I need to somehow foreach through all the comments and based on their user_id to add a new key-pair value with username-username and send it to the view afterwards. Unfortunately, I'm having trouble figuring how to do that.
public function specificImage($id){
$similarImages = null;
$image = Image::with('comments.user')->find($id);
$subImages = Image::where('parent_id', $id)->get();
$views = $image->views;
$image->views = $views + 1;
$image->save();
$authorId = $image->user_id;
$author = User::find($authorId);
$comments = Comment::where('image_id', $id)->get();
$recentImages = Image::where('parent_id', NULL)->where('user_id', $authorId)->orderBy('created_at', 'desc')->limit(9)->get();
$tag = Tag::whereHas('images', function($q) use ($id) {
return $q->where('taggable_id', $id);
})->first();
if (!empty($tag)) {
$tagId = $tag->id;
}
if (!empty($tagId)) {
$similarImages = Image::where('parent_id', NULL)->whereHas('tags', function($q) use ($tagId) {
return $q->where('tag_id', $tagId);
})->orderBy('created_at', 'desc')->limit(9)->get();
}
return view('specificImage', ['image' => $image,'subImages' => $subImages, 'recentImages' => $recentImages, 'similarImages' => $similarImages, 'author' => $author, 'comments' => $comments]);
}
Table:
Table: Comments
Columns: id, user_id, image_id, comment
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->morphToMany('App\Tag', 'taggable');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function updateVotes()
{
$this->upvotes = Vote::where('image_id', $this->id)->where('vote', true)->count();
$this->downvotes = Vote::where('image_id', $this->id)->where('vote', false)->count();
$this->save();
}
public function updateComments()
{
$this->comments = Comment::where('image_id', $this->id)->count();
$this->save();
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function image(){
return $this->belongsTo('App\Image');
}
public function user(){
return $this->belongsTo('App\User');
}
}
User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function images(){
return $this->hasMany('App\Image');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function roles(){
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function hasAnyRole($roles) {
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)){
return true;
}
}
} else {
if ($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if ($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
}
Blade
#extends('layouts.app')
#section('content')
<div class="specific-image-flexbox">
<div class="specific-image-column">
<div class='specific-image-container'>
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$image->file_name)}}' alt='Random image' />
#foreach($subImages as $subImage)
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$subImage->file_name)}}' alt='Random image' />
#endforeach
</div>
</div>
<div class="artwork-info-column">
<div class="artwork-info-container">
<p class='title'>{{ $image->name }}<p>
<p class='author'>на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
#if(Auth::user())
#if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
<a class='placeholderDelete' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'><i class="far fa-trash-alt"></i> Изтрий изображението</a>
#endif
#endif
<p class='description'>{{ $image->description }}</p>
<p class='description'>Техника: {{ $image->medium }}</p>
<p><i class="far fa-eye"></i> {{ $image->views }} Преглеждания</p>
<p><i class="far fa-thumbs-up"></i> {{ $image->upvotes }} Харесвания</p>
<p class='commentsCount'><i class="far fa-comments"></i> {{ $image->comments }} Коментари</p>
<a class='downloadImage' href="{{url("storage/uploads/images/specificImages/".$image->file_name)}}" download="{{ $image->name }}"><i class="fas fa-file-download"></i> Изтегли</a>
<!--<a class='placeholderDelete fas fa-expand' href='{{url("storage/uploads/images/specificImages/".$image->file_name)}}'></a>-->
<div class='social-container'>
<div class="addthis_inline_share_toolbox"
data-url="{{ url()->full() }}"
data-title="{{ $image->name }} by {{ $author->username }}"
data-description="{{ $image->description }}"
data-media="{{url("storage/uploads/images/specificImages/".$image->file_name)}}">
</div>
</div>
#if(!empty($recentImages))
#if(count($recentImages) >= 9)
<p class='author'>Още произведения на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
<div class="more-images-container">
#foreach($recentImages as $recentImage)
<div class="more-images-container-element">
<a href='{{url("image/".$recentImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$recentImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#if(!empty($similarImages))
#if(count($similarImages) >= 9)
<p class='similar-images'>Подобни произведения</p>
<div class="similar-images-container">
#foreach($similarImages as $similarImage)
<div class="similar-images-container-element">
<a href='{{url("image/".$similarImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$similarImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#auth
<div class='postComments'>
<form method='POST' action=''>
<textarea class='comment-section' name='comment'></textarea>
<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
<input type="hidden" name="image_id" value="{{ $image->id }}">
<button class='postComment submit' type='submit' name='commentSubmit'>Изпрати</button>
</form>
</div>
#endauth
<div class='comments'>
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach
</div>
</div>
</div>
</div>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment') }}';
var urlLike = '{{ route('vote') }}';
</script>
#endsection
I would suggest adding the user relationship to your Comment model as well:
class Comment extends Model
{
public function image()
{
return $this->belongsTo('App\Image');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
You can then eager load the relationships and then access them in your blade file:
public function specificImage($id)
{
$image = Image::with('comments.user')->find($id);
return view('specificImage', ['image' => $image]);
}
Then in your blade file you would have something like:
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach

How to order in Laravel high to low , low to high products - by price with this code?

How to order in Laravel high to low , low to high products - by price with this code? I got it all for a default presentation but i want to add 2 links to make quesy string so only when i click them the products will be ordered like high to low or low to high - other wise when it is not clicked on any links its ordered by default - DESC OR ASC
This is the code by order: MODEL CONTROLLER HTML:
static public function getProducts($url_category, &$data) {
$data['products'] = [];
if ($category = Categorie::where('url', '=', $url_category)->first()) {
$category = $category->toArray();
$data['title'] = $data['title'] . $category['title'];
$data['url_category'] = $url_category;
if ($products = Categorie::find($category['id'])->products) {
$data['products'] = $products->toArray();
}
}
}
function __construct() {
parent::__construct();
$this->middleware('adminAuth');
}
public function index() {
self::$data['products'] = Product::all()->toArray();
return view('cms.products', self::$data);
}
public function create() {
self::$data['categories'] = Categorie::all()->toArray();
return view('cms.add_product', self::$data);
}
public function store(ProductRequest $request) {
Product::save_new($request);
return redirect('cms/products');
}
public function show($id) {
self::$data['product_id'] = $id;
return view('cms.delete_product', self::$data);
}
public function edit($id) {
self::$data['categories'] = Categorie::all()->toArray();
self::$data['product'] = Product::find($id)->toArray();
return view('cms.edit_product', self::$data);
}
public function update(ProductRequest $request, $id) {
Product::update_product($request, $id);
return redirect('cms/products');
}
public function destroy($id) {
Product::destroy($id);
Session::flash('sm', $request['title'] . ' has been deleted');
return redirect('cms/products');
}
#if($products)
<a href='{{url('shop/' . $url_category . '?order=high')}}' class='btn btn-link'>From High to Low</a>|
<a href='{{url('shop/' . $url_category . '?order=low')}}' class='btn btn-link' style='color:purple;'>From Low to High</a>
<div class="row">
#foreach($products as $row)
<div class="col-md-6 col-sm-6">
<h3>{{ $row['title'] }}</h3>
<p><img alt="{{ $row['title'] }}" border="0" width="200" height="200" src="{{ asset('images/' . $row['image']) }}"></p>
<p>{!! $row['article'] !!}</p>
<p><strong>Price on site: </strong>{{ $row['price'] }}$</p>
<p>
View Product Details
<input #if( Cart::get($row['id'] )) disabled="disabled" #endif data-id="{{ $row['id'] }}" type="button" class="add-to-cart-btn btn btn-success" value="+ Add To Cart"/>
</p>
</div>
#endforeach
</div>
#else
<div class="row">
<div class="col-md-12">
<p><ans>No Products For This Category...</ans></p>
</div>
</div>
#endif
You can use the usort() function in your controller:
$data['products'] = $products->toArray();
if (request()->has('order') {
usort($data['products'], function($a, $b) {
return (request('order') == 'high') ? $b['price'] -
$a['price'] : $a['price'] - $b['price'];
});
}
You might want to consider to not cast $products to an array, but keep it as a collection instead. That way you can use Laravel's sortBy() method to sort the collection in a legible way.
// $order can be 'asc' or 'desc', which you determine in your controller
#foreach ($products->sortBy('column', $order) as $row)
See documentation here: Collections / sortBy()

Messages view show same username on from/to fields in Laravel

I have messaging system where users can write messages to administrator. The system works great except when Administrator open to read some message the name which should display from who is the message(username) shows the admin username instead.
On the front end user side all is correct.
I can't see where is the problem. Here is the admin message controller
public function messagesView($userId) {
/** #var User $user */
$user = User::where('user_id', $userId)->first();
if (!$user) {
App::abort(404);
}
$messages = $user->messages()->orderBy('created_at', 'asc')->get();
return View::make('site.admin.messages_view', [
'messages' => $messages
]);
}
public function messagesViewSubmit($userId) {
/** #var User $user */
$user = User::where('user_id', $userId)->first();
if (!$user) {
App::abort(404);
}
$validatorRules = array(
'message' => 'required|min:5',
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/admin/messages/view/' . $userId)->withErrors($validator->errors())->withInput(Input::all());
}
$message = new Message;
$message->user_id = $userId;
$message->text = Input::get('message');
$message->read_state = 0;
$message->from_admin = 1;
$message->save();
return Redirect::to('/admin/messages/view/' . $userId)->with('message_success', 'Message sent.');
}
Here is the view
#foreach($messages as $message)
#if($message->from_admin)
<div class="row">
<div class="media well col-xs-9">
<div class="media-left">
<img class="media-object" src="{{ URL::to('/img/admin.png') }}" alt="">
</div>
<div class="media-body user-message">
<h4 class="media-heading"><span style="font-weight: bold; color: red">Administrator {{{ $user['user_id'] }}}</span></h4>
<span>{{ $message->created_at }}</span>
<hr class="hr-sm-gray" />
{{ nl2br($message->text) }}
</div>
</div>
</div>
#else
<div class="row">
<div class="media well col-xs-9 col-xs-offset-3">
<div class="media-body text-right user-message">
<h4 class="media-heading">{{{ $user['username'] }}} - {{{ $user['user_id'] }}}</h4>
<span>{{ $message->created_at }}</span>
<hr class="hr-sm-gray" />
{{ nl2br(e($message->text)) }}
</div>
<div class="media-right">
<img class="media-object" src="{{ URL::to('/img/user.png') }}" alt="">
</div>
</div>
</div>
#if($message->read_state == 0)
{{ $message->markAsRead() }}
#endif
#endif
#endforeach
Messages model
protected $table = 'messages';
protected $primaryKey = 'message_id';
public function user() {
return $this->belongsTo('User', 'user_id', 'user_id');
}
public function markAsRead() {
$this->read_state = '1';
$this->save();
And this I have in User model
public function messages() {
return $this->hasMany('Message', 'user_id', 'user_id');
}
May be is session related.. here is what I have in BaseController where I check if user is logged in and if is admin or not.
protected function setupLayout()
{
if (!is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
$user = self::getCurrentUser();
View::share('isLoggedIn', self::isLoggedIn());
View::share('user', $user);
if (self::isLoggedIn()) {
View::share('messagesCount', $user->messages()->where('read_state', '0')->where('from_admin', '1')->count());
}
}
public static function isLoggedIn() {
$user = Session::get('user', null);
if ($user !== null) {
return true;
} else {
return false;
}
}
public static function isAdmin() {
if (!self::isLoggedIn()) {
return false;
}
$user = self::getCurrentUser();
return (bool)$user->is_admin;
}
public static function getCurrentUser() {
if (!self::isLoggedIn()) {
return null;
}
$user = Session::get('user', null);
if (self::$user == null) {
$user = User::where('user_id', $user['user_id'])->first();
self::$user = $user;
}
return self::$user;
}
It is because you select current user username in else block
<h4 class="media-heading">{{{ $user['username'] }}} - {{{ $user['user_id'] }}}</h4>
Try to replace it to
<h4 class="media-heading">{{{ $message->user->username }}} - {{{ $user['user_id'] }}}</h4>
This way you will select user from users table.

Categories