Can not update a boolean value in table by vue and laravel - laravel

I have a boolean field when I try to update from false to true for a single or multiple records it works but when trying to update it back to false it works for the first record only and can not repeat to update multiple records at the same time without refreshing the page 1- my vue component that handles the request is like this:
<template>
<div v-for="(channel, index) in items" :key="channel.id">
<a href="" #click.prevent="toggleVisibility(channel)">
<i v-if="channel.active" class="fas fa-stop default-stop" data-toggle="tooltip" title="Stop Channel">
</i>
<i v-else class="fas fa-play" data-toggle="tooltip" title="Start Channel"></i>
</a>
</div>
</template>
export default {
name: "Channels",
props: ['allChannels'],
data() {
return {
items: this.allChannels
}
},
methods: {
toggleVisibility(channel) {
axios[channel.active ? 'delete' : 'post'](`/visible-channels/${channel.name}`);
}
}
}
and my routes:
Route::post('/visible-channels/{channel}', 'ChannelsController#activate');
Route::delete('/visible-channels/{channel}', 'ChannelsController#deactivate');
my controller:
public function activate(Channel $channel, Request $request)
{
if ($request->method() == 'POST') {
$channel->update(['active' => true]);
}
return back();
}
public function deactivate(Channel $channel, Request $request)
{
if ($request->method() == 'DELETE') {
$channel->update(['active' => false]);
}
}
The model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class Channel extends Model
{
protected $guarded = [];
protected $casts = [
'active' => 'boolean',
];
protected static function boot()
{
parent::boot();
static::updating(function () {
return Cache::forget('activeChannels');
});
}
public function getRouteKeyName()
{
return 'name';
}
}

Since laravel stores boolean as 1 and 0 in database, You should probably set active property to boolean in your model
That's because laravel treat false as string so when you set active to false it compares it as 'false' == true which is true so it stores 1 in database.
class Channel extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'active' => 'boolean',
];
}

I figured it out just change in the boot function to wait until the update finish
static::updated(function () {
return Cache::forget('activeChannels');
});

Related

DB::table('table')->select returning empty string Laravel 6

I am using Laravel 6 with Vue axios, I want to populate a form-select with what I have in my "fjl_groups" table. But everytime I check the console for the result it is returning me an empty string, any idea why is this? My Laravel logs aren't returning any error either, so I have no idea what's going on.
Vue's part
<b-col cols="4">
<label for="editorial">Group</label>
<b-form-select v-model="group" :options="groups" id="groups" name="groups"></b-form-select>
</b-col>
<script>
export default {
data() {
return {
group: null,
groups: [{
value: null,
text: 'Select'
}]
}
},
created(){
axios.get('/clubs/create')
.then(res => {
this.groups = res.data;
console.log(this.groups);
}).catch(e => {
console.log(e);
})
},
}
}
</script>
I have a club and I want to assign a group for it from the ones I have added in my database, this is why I have it like that.
My controller (ClubsController)
use Illuminate\Support\Facades\DB;
use App\Models\Club;
use App\Models\Group;
public function create(Request $request)
{
if($request->ajax()){
DB::table('fjl_groups')->select('id as value', 'nom as text')->get();
}
else{
return view('clubs.create');
}
}
Group Model
class Group extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'fjl_groups';
public $timestamps = false;
}
You are not returning a value. You're just performing the select.
Try returning it:
return response()->json([
'data' => DB::table('fjl_groups')->select('id as value', 'nom as text')->get()
]);

Not found for some routes

I have a problem with some of my routes in Laravel. this my code in web.php file:
Route::group(['namespace' => 'Admin', 'middleware' => ['auth:web']], function () {
Route::get('/admin/audio/create/{audio?}', 'AdminAudioController#create')->name('admin.audioCreate');
Route::get('/admin/article/create/{article?}', 'AdminArticleController#create')->name('admin.articleCreate');
}
and this my link in blade
<i class="fa fa-edit"></i>
<i class="fa fa-edit"></i>
and this are my Controllers:
AdminAudioController
<?php
namespace App\Http\Controllers\Admin;
use App\Article;
use App\Http\Requests\ArticleRequest;
class AdminArticleController extends AdminController
{
public function index()
{
$articleList = Article::where('removed', false)->latest()->paginate(10);
return view('admin.article.archive', compact('articleList'));
}
public function create(Article $article = null)
{
return view('admin.article.create', compact('article'));
}
}
AdminArticleController
<?php
namespace App\Http\Controllers\Admin;
use App\Article;
use App\Http\Requests\ArticleRequest;
class AdminArticleController extends AdminController
{
public function index()
{
$articleList = Article::where('removed', false)->latest()->paginate(10);
return view('admin.article.archive', compact('articleList'));
}
public function create(Article $article = null)
{
return view('admin.article.create', compact('article'));
}
}
but my second link with name "admin.articleCreate" doesn't work and get "404 not found" what should I do?
and this is my article model
class Article extends Model
{
protected $primaryKey = 'articleId';
use Sluggable;
protected $fillable = [
'title',
'subTitle1', 'subTitle2',
'image',
'description',
'body',
'enable',
];
protected $casts = [
'image' => 'array'
];
/**
* Return the sluggable configuration array for this model.
*
* #return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function getRouteKeyName()
{
return 'slug';
}
}
When you call the method create(Article $article = null) on your controller, Laravel uses Model Binding to resolve your model and the model binding uses the method you have added to your model
public function getRouteKeyName()
{
return 'slug'; // by default it will be $primaryKey which is 'id'
}
In short, Laravel will try to use slug to find your model while your giving him articleId
So to fix it you have few options
Using the slug in the URL (the one I would recommend)
// blade.php
<i class="fa fa-edit"></i>
Using the primary articleId in the URL
// blade.php
<i class="fa fa-edit"></i>
// Article.php.php
public function getRouteKeyName()
{
return 'articleId';
}
Using a query
// blade.php
<i class="fa fa-edit"></i>
//Controller.php
public function create($article = null)
{
$article = Article::where('YOUR_FIELD', $article)->firstOrFail();
return view('admin.article.create', compact('article'));
}
you have code
return view('admin.article.create', compact('$article'));
but need
return view('admin.article.create', compact('article'));
I can see you have mentioned $article in side compact.
Can you please check once, I think the create method should look like this:
public function create(Article $article = null)
{
return view('admin.article.create', compact('article'));
}

Laravel Has Undefined Constant 'App\App\projects

I have created a model called company and projects, I need to show projects under a company. The company is showing fine, but when I added a project relation to the model, it displays an error. I am a newbie to Laravel.
Undefined constant 'App\App\projects' (View:
C:\xampp\htdocs\testdrive\resources\views\companies\show.blade.php)
C:\xampp\htdocs\testdrive\app\company.php
Model
use Illuminate\Database\Eloquent\Model;
class company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User);
}
public function projects()
{
return $this->hasMany(App\projects);
}
}
show.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<!-- Jumbotron -->
<div class="jumbotron">
<h1>{{$company->name}}</h1>
<p class="lead">{{$company->description}}</p>
</div>
<!-- Example row of columns -->
<div class="row">
#foreach($company->projects as $projects)
<div class="col-lg-4">
<h2>{{$projects->name}}</h2>
<p class="text-danger">{{$projects->description}} </p>
<p>
<a class="btn btn-primary" href="/projects/{{$projects->id}}" role="button">View Project</a>
</p>
</div>
#endforeach
</div>
</div>
#endsection
You've got a typo! namespaces should be strings:
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\projects');
}
You are missing class keyword in your model
class company extends Model
{
//
protected $fillable=[
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo(App\User::class);
}
public function projects()
{
return $this->hasMany(App\projects::class);
}
}
Hope this helps
Either pass class of the model or it's namespace within questions
public function user()
{
return $this->belongsTo(App\User::class); //or $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany(App\Project::class);
}
Aside from using quotes to reference the model as mentioned above.
It might also be necessary to define the namespace of your class.
Sidenote: it's also a Laravel naming convention to use PascalCase for classnames (ie. Company, WetCamel, FooBarClass)
namespace App\Company;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $fillable = [
'name',
'description',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function projects()
{
return $this->hasMany('App\Projects');
}
}
Use '' this to call the model.
Correct your syntax as:
public function projects()
{
return $this->hasMany('App\projects');
}

How to show the comments which belongs to the post?

I'm creating a news feed kind of thing where users can post anything and the post will have comments also. I'm able to create the newsfeed and the comment section, but my real problem is I'm not able to show the comments which belongs to the post. Right now all the comments are displayed under every news feed. Though I've declared the eloquent relationship between feed and comment but still I'm not able to save the feed_id in comment table.
This is my FeedsController:-
<?php namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;
class FeedsController extends Controller
{
public function index() {
$comments = Comment::latest()->get();
$feeds = Feed::where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index')->with('feeds', $feeds)->with('comments', $comments)->with('blogs', $blogs);
}
public function store(Requests\CreateFeedRequest $request){
$requet = $request->all();
$request['user_id'] = Sentinel::getuser()->id;
Feed::create($request->all());
return redirect('home');
}
public function storecomment(Requests\CommentRequest $request, Feed $feed)
{
$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
return redirect('home');
}
}
This is the models:
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Feed model:
use Illuminate\Database\Eloquent\Model;
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
User model:-
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
This is my feed.blade.php where I'm displaying the feeds output and commnets
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
</div>
</article>
#endforeach
Can anyone tell me how to store the feed_id into comment table and displaying the comments according to the feed. Thank You. I'm using Laravel 5.1
Based on our lengthy convo -
To save the feed_id (which is our foreign key for future relationships), you need to set/send the feed_id in your POST request. Laravel is not magic and won't know this automatically. You can do this by adding a hidden input, like so:
<input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" />
In your FeedController, change your index to this:
public function index() {
// $comments = Comment::latest()->get(); remove this
// notice the "with" below. I'm eager loading in relations here
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index', compact('feeds', 'blogs'));
}
Feed Model should have the correct relationships, as below:
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
public function comments()
{
return $this->hasMany('App\Comment', 'feed_id', 'feed_id');
}
}
Comment Model should have the correct relationships, as below:
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
}
Now you should be able to run your foreach as you currently have it.

Laravel: Passing data to default.blade.php from base controller

I have a base controller with a method to return a twitter feed to my view.
I want to move this in the view from the page view to the default blade to reduce redundancy as it will be appearing site wide. How do I pass data from the base controller to blade?
I can send it to my view from the page controller like so:
public function get_index()
{
..................
$this->layout->nest('content', 'home.index', array(
'tweets' => $this->get_tweet()
));
}
and in the view, output it like this:
if ($tweets)
{
foreach ($tweets as $tweet)
{
..............
I want to do all this from within default.blade.php and my Base_Contoller:
<?php
class Base_Controller extends Controller {
/**
* Catch-all method for requests that can't be matched.
*
* #param string $method
* #param array $parameters
* #return Response
*/
public function __call($method, $parameters)
{
return Response::error('404');
}
public function get_tweet()
{
...........
return $tweets;
}
}
How is this possible?
//////////////////////UPDATE/////////////////////////////
application/models/tweets.php
<?php
class Tweets {
public static function get($count = 3)
{
Autoloader::map(array(
'tmhOAuth' => path('app').
'libraries/tmhOAuth-master/tmhOAuth.php',
'tmhUtilities' => path('app').
'libraries/tmhOAuth-master/tmhUtilities.php'
));
$tmhOAuth = new tmhOAuth(array(
'consumer_key' => 'xxx',
'consumer_secret' => 'xxx',
'user_token' => 'xxxxx',
'user_secret' => 'xxxxx',
'curl_ssl_verifypeer' => false
));
$code = $tmhOAuth->request('GET',
$tmhOAuth->url('1.1/statuses/user_timeline'), array(
'screen_name' => 'xxx',
'count' => $count
));
$response = $tmhOAuth->response['response'];
$tweets = json_decode($response, true);
return $tweets;
}
}
application/views/widgets/tweets.blade.php
#foreach ($tweets)
test
#endforeach
application/views/layouts/default.blade.php
....
{{ $tweets }}
....
application/composers.php
<?php
View::composer('widgets.tweets', function($view)
{
$view->tweets = Tweets::get();
});
View::composer('layouts.default', function($view)
{
$view->nest('tweets', 'widgets.tweets');
});
application/controllers/base.php
<?php
class Base_Controller extends Controller {
/**
* Catch-all method for requests that can't be matched.
*
* #param string $method
* #param array $parameters
* #return Response
*/
public $layout = 'layouts.default';
public function __call($method, $parameters)
{
return Response::error('404');
}
}
application/controllers/home.php
<?php
class Home_Controller extends Base_Controller {
public $layout = 'layouts.default';
public $restful = true;
public function get_index()
{
Asset::add('modernizr', 'js/thirdparty/modernizr.js');
Asset::add('jquery',
'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
Asset::add('scripts', 'js/scripts.js');
$this->layout->title = 'title';
$this->layout->nest('content', 'home.index', array(
//'data' => $some_data
));
}
}
Is giving me an
Undefined variable: tweets
error
Step 1 - Make a view just for your tweets, let's call it widgets/tweets.blade.php, that will accept your $tweets data. This makes it very easy to cache the tweets view in the future if you want a little more performance. We also want a model that will generate the tweet data for you.
Step 2 - Pass the tweet data into your tweets view, let's use a View Composer for this so the logic is kept with (but outside) the view.
Step 3 - Create your default layout, let's call this layout/default.blade.php. This will accept $content and $tweets. We'll nest the tweets view with another View Composer. You can nest the $content in your controller actions.
Step 4 - Set the $layout on your Base_Controller.
Step 5 - Profit!
Note - If these are your first view composers then you'll need to include them in application/start.php
// application/models/tweets.php
class Tweets {
public static function get($count = 5)
{
// get your tweets and return them
}
}
// application/views/widgets/tweets.blade.php
#foreach ($tweets)
{{-- do something with your tweets --}}
#endforeach
// application/views/layouts/default.blade.php
<section class="main">{{ isset($content) ? $content : '' }}</section>
<aside class="widget widget-tweets">{{ $tweets }}</aside>
// application/composers.php
View::composer('widgets.tweets', function($view)
{
$view->tweets = Tweets::get();
});
View::composer('layouts.default', function($view)
{
$view->nest('tweets', 'widgets.tweets');
});
// application/start.php (at the bottom)
include path('app').'composers.php';
// application/controllers/base.php
class Base_Controller extends Controller {
public $layout = 'layouts.default';
}
// application/controllers/home.php
class Home_Controller extends Base_Controller {
public $restful = true;
public function get_index()
{
$this->layout->nest('content', 'home.welcome');
}
}
View::share('key', 'value');
in you view use (Blade syntax)
{{$key}}
or (PHP syntax)
echo $key;

Resources