I am new to laravel and creating todo list.
I try to toggle checkbox.
BUt in checked method(the bottom of PostController), I can't even change text in the first place.
What's wrong with checked method?
I expect a problem in web.php.
I'm using laravel8.
thankyou for your help!
What's wrong with checked method?
(((PostController.php)))
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use App\Http\Requests\PostRequest;
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->get();
return view('index')
->with(['posts' => $posts]);
}
public function show(Post $post)
{
return view('posts.show')
->with(['post' => $post]);
}
public function checked(Post $post)
{
// $post->is_done = !$post->is_done;
$post->title = 'hogehoge';
$post->save();
return redirect()
->route('posts.index');
}
}
(((web.php)))
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('/', [PostController::class, 'index'])
->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])
->name('posts.show')
->where('post', '[0-9]+');
Route::patch('/posts/{post}/checked', [PostController::class, 'checked'])
->name('posts.checked')
->where('post', '[0-9]+');
(((post table column)))
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->boolean('is_done')->default(false);
$table->timestamps(); // created_at, updated_at
});
}
Related
I want to retrieve all comments which belong to active posts.
I have a local scope on my Posts model looking like this.
public function scopePublic($query) {
return $query->whereHas('post', function ($q) {
$q->where('is_public', true);
});
}
Which works fine, but breaks with PHP message: PHP Fatal error: Allowed memory size of X bytes exhausted as soon as I want to convert it to a global scope like this:
static::addGlobalScope('is_public', function (Builder $builder) {
return $builder->whereHas('post', function ($q) {
$q->where('is_public', true);
});
});
My end goal is for all comment queries only to show public comments, unless I specifically ask not to.
I've been through quite a few solutions. I've tried joining the post on the comments, and I tried adding a sub-select to no luck.
$builder->addSelect(['is_public' => Post::select('is_private')
->whereColumn('id', 'comment.post_id')->limit(1)
]);
$builder->join('posts','posts.id','=','comments.post_id')
->where('comments.is_private', false);
Make a new class PublicScope
use Illuminate\Database\Eloquent\Scope;
class CommentPublicScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* #param \Illuminate\Database\Eloquent\Builder $builder
* #param \Illuminate\Database\Eloquent\Model $model
* #return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->whereHas('post', function ($q) {
$q->where('is_public', true);
});
}
}
Then you can add the global scope
Class Comment extends Model
{
protected static function boot()
{
parent::boot();
static::addGlobalScope(new CommentPublicScope);
}
}
I am going to use DynamicPDF plugin to export to pdf some fields from backend on update/edit view of my plugin in OctoberCMS, can someone help me?
on plugin controller i have this call:
<?php namespace Vimagem\Pacientes\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
use Renatio\DynamicPDF\Classes\PDF;
use Renatio\DynamicPDF\Classes\PDFWrapper;
class Pacientes extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Vimagem.Pacientes', 'main-menu-item');
}
/** PDF **/
public function pdf($id)
{
return PDF::loadTemplate('export-data-pdf')->stream('download.pdf');
}
}
On the PDF Template (export-data-pdf) i need to call some form fields from one client:
{{ name }}
{{ address }}
{{ phone }}
etc...
but i canĀ“t get the fields show up, what its wrong ?
Thank you,
Vitor
This code was found in the plugins documents.
use Renatio\DynamicPDF\Classes\PDF; // import facade
...
public function pdf()
{
$templateCode = 'renatio::invoice'; // unique code of the template
$data = ['name' => 'John Doe']; // optional data used in template
return PDF::loadTemplate($templateCode, $data)->stream('download.pdf');
}
I have used this plugin and it works well. You need to pass in data to the PDF stream.
This is done, worked around a solution for this.
Here is the controller application:
<?php namespace Vimagem\Pacientes\Controllers;
use Backend\Classes\Controller;
use BackendMenu;
use Renatio\DynamicPDF\Classes\PDFWrapper;
use Vimagem\Pacientes\Models\Paciente;
use \October\Rain\Database\Traits\Validation;
use Str;
class Pacientes extends Controller
{
public $implement = [ 'Backend\Behaviors\ListController', 'Backend\Behaviors\FormController', 'Backend\Behaviors\ReorderController' ];
public $listConfig = 'config_list.yaml';
public $formConfig = 'config_form.yaml';
public $reorderConfig = 'config_reorder.yaml';
public function __construct()
{
parent::__construct();
BackendMenu::setContext('Vimagem.Pacientes', 'main-menu-item');
}
/**** PDF Export ***/
public function pdf($id)
{
$paciente = Paciente::find($id);
if ($paciente === null) {
throw new ApplicationException('User not found.');
}
$filename = Str::slug($paciente->nome) . '.pdf';
try {
/** #var PDFWrapper $pdf */
$pdf = app('dynamicpdf');
$options = [
'logOutputFile' => storage_path('temp/log.htm'),
];
return $pdf
->loadTemplate('export-data-pdf', compact('paciente'))
->setOptions($options)
->stream($filename);
} catch (Exception $e) {
throw new ApplicationException($e->getMessage());
}
}
}
Now i can use partials on the template like this:
<p>{{ paciente.nome }}</p>
<p>{{ paciente.morada }}</p>
etc...
Thank you all that try to helped me.
Vitor
How convert this Raw SQL to Eloquent Database in my API Controller?
What i'm tried is i wanna get data from Two Tables from My API Controller.
First: Formc_image Table which is general information about data
Second: Formc_image_detail which is detail and path of data
They are related by ID.
This is my API Controller FormCController.php
SELECT *
FROM formc_image_detail
WHERE id_tps=$id_tps AND jenis_pemilihan=$election_id
AND versi = (SELECT MAX(versi) FROM formc_image WHERE id_tps=id_tps AND jenis_pemilihan=$election_id)
ORDER BY no_lembar ASC
This is my Model FormCImageDetail
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImageDetail extends Model
{
protected $table = 'formc_image_detail';
public function formc_image(){
return $this->belongsTo('App\Models\FormCImage');
}
}
This is my FormCImage Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImage extends Model
{
protected $table = 'formc_image';
}
I was make this code in My API Controller:
return response(FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->orderBy('no_lembar', 'ASC')->paginate(100)->jsonSerialize(), Response::HTTP_OK);
But it still error.
This is my Migration:
Schema::create('formc_image', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->string('jenis_pemilihan');
$table->timestamps();
}
Schema::create('formc_image_detail', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->integer('no_lembar');
$table->string('jenis_pemilihan');
$table->char('url_image', 100);
$table->timestamps();
}
Use this:
return FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->where('versi', function($query) use($election_id) {
$query->select(DB::raw('max(versi)'))
->from('formc_image')
->whereColumn('id_tps', 'formc_image_detail.id_tps')
->where('jenis_pemilihan', $election_id);
})
->orderBy('no_lembar')
->paginate(100);
I just started with learning how to test within Laravel. I came across some problems though..
I'm testing my controller and want to check if a View has a variable assigned.
My controller code:
class PagesController extends \BaseController {
protected $post;
public function __construct(Post $post) {
$this->post = $post;
}
public function index() {
$posts = $this->post->all();
return View::make('hello', ['posts' => $posts]);
}
}
And my view contains a foreach loop to display all posts:
#foreach ($posts as $post)
{{post->id}}
#endforeach
Last but not least my test file:
class PostControllerTest extends TestCase {
public function __construct()
{
// We have no interest in testing Eloquent
$this->mock = Mockery::mock('Eloquent', 'Post');
}
public function tearDown()
{
Mockery::close();
}
public function testIndex() {
$this->mock->shouldReceive('all')->once()->andReturn('foo');
$this->app->instance('Post', $this->mock);
$this->call('GET', '/');
$this->assertViewHas('posts');
}
}
Now comes the problem, when I run "phpunit" the following error appears:
ErrorException: Invalid argument supplied for foreach()
Any ideas why phpunit returns this error?
Your problem is here:
$this->mock->shouldReceive('all')->once()->andReturn('foo');
$this->post->all() (which is what you're mocking) should return an array, and that's what your view expects. You're returning a string.
$this->mock->shouldReceive('all')->once()->andReturn(array('foo'));
should take care of the error you have, though you'll then get an error of the "Getting property of non-object" type.
You could do this:
$mockPost = new stdClass();
$mockPost->id = 1;
$this->mock->shouldReceive('all')->once()->andReturn(array($mockpost));
You should mock the view as well:
public function testIndex() {
$this->mock->shouldReceive('all')->once()->andReturn('foo');
$this->app->instance('Post', $this->mock);
View::shouldReceive('make')->with('hello', array('posts', 'foo'))->once();
$this->call('GET', '/');
}
I am trying to get the user id but no luck so far...
echo Yii::app()->user->id;
and
echo Yii::app()->user->getId();
return the name of user which is weird.
Any idea what is wrong?
Yii::app()->user returns a component CWebUser by default.
When you want to get some additional information about user, you need to extend this component.
Create a file WebUser.php in your components folder. (my example below)
class WebUser extends CWebUser {
/**
* Gets the FullName of user
*
* #return string
*/
public function getFullName()
{
return $this->_model->first_name . ' ' .$this->_model->last_name;
}
}
In your config file find section
'components'=>array(
'user'=>array(
'class'=>'WebUser'
)
)
if there is no this section , just create it. And change 'class'=> to WebUser'.
you should have getId function in user Identity
Or you are can use setState:
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=Users::model()->findByAttributes(array('mail'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password!==md5($this->password."325"))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->_id = $record->id;
$this->setState('role', $record->active);
$this->setState('mail', $record->mail);
$this->setState('name', $record->name);
$this->setState('surname', $record->surname);
$this->setState('mobile', $record->mobile);
$this->setState('adress', $record->adress);
$record->count_login += 1;
$record->update();
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
<?php echo Yii::app()->user->name." ".Yii::app()->user->surname; ?>
Use getid function in the Component/Useridentity to get user id and name etc..
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$users=Users::model()->find("email_id='$this->username'");
$this->_id=$users->user_id;
}
public function getId(){
return $this->_id;
}
}
if you want to display it on a views this should do:
echo Yii::$app->user->id;