I have two tables: users and posts. I made relation between these two tables. When I try to save, the post created by the user to posts to a table. It does not pass the user's id. Please check the below code:
User Model ( App\User.php )
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts()
{
$this->hasMany('App\Post');
}
}
Post Model ( App\Post.php )
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
$this->belongsTo('App\User');
}
}
Post Controller ( App\Http\Controllers\PostController.php )
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
class PostController extends Controller
{
public function postCreatePost(Request $request)
{
//validation here will come
$post = new Post();
$post->body = $request['body'];
$request->user()->posts()->save();
return redirect()->route('dashboard');
}
}
Errors
I found the solution. So, I will post the answer of my question.
I get the current logged in user'id from Auth::id();
So I changed my codes as below
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
class PostController extends Controller
{
public function postCreatePost(Request $request)
{
//validation here will come
$post = new Post();
$post->body = $request['body'];
$post->user_id = \Auth::id();
$post->save();
return redirect()->route('dashboard');
}
}
Related
Extended class '\Magento\Framework\App\Helper\AbstractHelper' is not marked as an API
Inspection info:
The extended class is not marked as an API.
<?php
namespace Vendor\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
class Customer extends AbstractHelper
{
...
Change
Magento\Framework\App\Helper\AbstractHelper
to
Magento\Framework\App\Config\ScopeConfigInterface;
Example:
<?php
declare(strict_types=1);
namespace Vendor\Module\Helper;
use Magento\Framework\App\Config\ScopeConfigInterface;
class Customer
{
protected $scopeConfigInterface;
public function __construct(
ScopeConfigInterface $scopeConfig
) {
$this->scopeConfigInterface = $scopeConfig;
}
public function getData(): string
{
return $this->scopeConfigInterface->getValue('web/secure/base_url')
}
}
I have 2 tables (projects and clients). A client can have many projects. A project belongs to one client.
Tables schema:
Client:
Schema::create('clients', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('contact_person');
$table->timestamps();
});
Projects:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->date('due');
$table->integer('client_id')->unsigned();
$table->foreign('client_id')->references('id')->on('clients');
$table->timestamps();
});
Here is the models:
Client Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
public function projects()
{
return $this->hasMany('App\Project');
}
}
Project Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
public function tasks()
{
return $this->hasMany('App\Task');
}
public function client()
{
return $this->belongsTo('App\Client');
}
}
Here are the controllers.
ClientsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ClientsController extends Controller
{
public function index()
{
$clients = Client::has('projects')->get();
return $this->hasMany('projects');
}
}
ProjectsController
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Client;
use Illuminate\Http\Request;
class ProjectsController extends Controller
{
public function index()
{
$projects = Project::find(1)->projects;
return $projects->all();
}
public function store(Request $request)
{
return $request->all();
}
}
Project.vue
<ul>
<li v-for="project in projects">
{{ project.name }}
// client's name here
</li>
</ul>
I want to return a query that will display all clients' name and their project name accordingly. All i can get for now is the project name only. Thank you.
Just after i post my question i found the solution. here it goes.
ProjectsController
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Client;
use Illuminate\Http\Request;
class ProjectsController extends Controller
{
public function index()
{
$projects = Project::with('client')->get();
return $projects->all();
}
public function store(Request $request)
{
return $request->all();
}
}
and the Project.vue
<ul>
<li v-for="project in projects">
{{ project.name }} || {{project.client.contact_person }}
</li>
</ul>
Basically, I see Eloquent (for that matter, any ORM) as overhead, as MongoDB itself deals with document objects.
I am looking to use native PHP MongoDB code with application wide database connection object, for a greater performance.
Any library or a simple way to achieve this?
I have read a few things and used PHP MongoDB driver with custom "Model" code, with base class like below:
AppModel.php
<?php
namespace App;
use MongoClient;
use MongoId;
use Log;
class AppModel {
public $collection;
public function __construct() {
$mongo = new MongoClient();
$model_name = (new \ReflectionClass($this))->getShortName();
$collection_name = str_plural(strtolower($model_name));
$this->collection = $mongo->selectCollection('proj_zabbit', $collection_name);
}
public function findById($id) {
return $this->collection->findOne(array(
'_id' => new MongoId($id)
));
}
// more wrapper functions ..
}
Extended model class:
<?php
namespace App;
class Message extends AppModel {
}
In Controller:
<?php namespace App\Http\Controllers;
use App\Message;
class MessagesController extends Controller {
public function __construct()
{
$this->Message = new Message;
}
public function get()
{
$id = Input::get('id');
$message = $this->Message->findById($id);
return $message;
}
}
i am using zend framework 1.10 with doctrine 2. i wonder if in my (doctrine) model class, isit a good idea to reference a variable set by my application (bootstrap.php, variable stored in Zend_Registry, i think its something like a global variable)
what i want to access is the doctrine entityManager. also i want the id of the logged in user
I am building a project with similar setup (ZF 1.10 + Doctrine2) and I've used dependency injection to deal with this situation, much like takeshin said. Here goes full project repository URL: https://bitbucket.org/phpfour/zf-doctrine2. Below are some code excerpts.
Here's my controller:
<?php
require_once APPLICATION_PATH . "/models/PostManager.php";
class IndexController extends Zend_Controller_Action
{
private $_em;
public function init()
{
$this->_em = $this->getInvokeArg('bootstrap')->getResource('doctrine');
}
public function indexAction()
{
$pm = new PostManager($this->_em);
$this->view->posts = $pm->getPublicPosts();
}
My entity manager (or service class):
<?php
class PostManager
{
protected $_em;
public function __construct(Doctrine\ORM\EntityManager $em)
{
$this->_em = $em;
}
public function getPublicPosts()
{
$query = $this->_em->createQuery('SELECT p FROM Entities\Post p WHERE p.visible = true');
$posts = $query->getResult();
return $posts;
}
Hope this helps!
you should simply use Zend_Auth for the logged-in-userId problem, then could do something like the following in your model
class Model extends BaseModel
{
public function something()
{
$auth = Zend_Auth::getInstance();
if ($auth->hasIdentity()) {
$loggedInUserId = $auth->getIdentity()->id;
}
}
}
There is nothing wrong with this approach (unless you are referring to singletons). Use dependency injection where possible.
However I'd create a service (or two) for this.
class Modulename_Services_Servicename
{
public function getCurrentUser() { ... }
public function getCurrentUserModel() { ... }
public function isLogged() { ... }
public function authenticate() { ... }
public function getSomeData()
{
$user = $this->getCurrentUser()
$model = new YourModel($user);
$query = ....;
$result = $query->execute();
return $result;
}
public function getSomeMoreData($usermodel) { ... }
}
Yall:
I have a simple question, it might be a simple configuration issue, but
I have a Model defined, and when I try to access it from a controller it
fails.
The Model is in the model directory, and when I look at the quickstart app,
it seems like this should work.
Here is my model:
<?php
class Application_Model_User {
protected $_user;
protected $_password;
protected $_userId; // very simple right
}
?>
My controller just stops.. here is the controller code:
<?php
class UserController extends Zend_Controller_Action {
public function init() {
}
public function indexAction() {
// display login form
$users = new Application_Model_User();
echo "test never echos.. stopped above ? weird huh.."; // fails before ..
}
?>
Thank you everyone,
In application.ini
appnamespace = "Application_"
App structure:
/application/
/models/
/User.php
Class definition:
class Application_Model_User {}
Should work OK.