the app currently has the ability to delete all tasks, but it needs to delete a task only if its owned by the user that is LOGGED in.
this is in php slim and im using eloquent.
here is what i currently have, it currently deletes all posts even if its not by the user.
Any suggestions, their isn't much documentation on eloquent in regards with slim. so im unsure.
todoscontroller.php
<?php
namespace App\Controllers;
use Slim\Http\Request;
use Slim\Http\Response;
use Illuminate\Database\Capsule\Manager as DB;
use App\Models\Task;
use App\Models\User;
use App\Auth\Auth;
class TodosController extends BaseController
{
public function deleteTodo($request, $response, $id)
{
// $sth = $this->db->prepare("DELETE FROM tasks WHERE id=:id");
// $sth->bindParam("id", $args['id']);
$owl = $id['id'];
$todos = Task::find($owl);
// $todos = $sth->fetchObject();
// $url = urlFor($todos);
$todos->delete();
return $response->withJson($todos)->withRedirect('/todos');
}
Good Question.
But have you seen the Slim Framework document?
There is a Middleware, and I am sure your could handle your request by the Middleware before it accesses the controller.
Related
I am working on a Laravel control panel project where we should be able to toggle from one site to another and get the detail of the site based on the ID passed in the route.
In itself this is quiet easy to do but as I will have several controllers using this technique it means for each controller and each controller instance I will have collect the site instance and it does not look very user friendly due to the many repetitions.
Here is what I have:
Route:
Route::get(
'cp/site/{website}/modules/feeds',
'App\Http\Controllers\Modules_sites\Feeds\FeedController#index'
)->name('module_site.feeds.index');
Model:
class Website extends Model
{
use HasFactory;
protected $primaryKey ='site_id';
}
The database is simple with an id (site_id) and name
Controller:
public function index(Website $website)
{
dd($website -> name);
}
The above is working fine but I am going to end with dozens of methods across multiple controllers doing the same thing, and what if changes are required.
I have looked at the ID of using the AppServiceProvider to create the Website instance and then pass it to the controllers and views but I can't do this as the route is not defined at this stage and I only seem to be able to pass this to the view.
Essentially, I am looking to create something similar to the auth()->user() method that is available from controllers and routes without the needs to pass it to each controller.
Is this possible?
Perhaps you could use middleware to set this value? Something like this to put it in the session globally:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckWebsite
{
public function handle(Request $request, Closure $next): mixed
{
$request->session()->put("website", $request->route("website"));
return $next($request);
}
}
Or this on a per-controller basis:
<?php
namespace App\Http\Controllers\Modules_sites\Feeds;
use App\Http\Controllers\Controller;
use Closure;
use Illuminate\Http\Request;
class FeedController extends Controller
{
public function __construct()
{
$this->middleware(function (Request $request, Closure $next) {
$this->website = $request->route("website");
return $next($request);
});
}
public function index()
{
dd($this->website->name);
}
}
Also worth mentioning that routes are not defined like that in Laravel 8 any longer. It should look like this:
Route::get(
'cp/site/{website}/modules/feeds',
[FeedController::class, 'index']
)->name('module_site.feeds.index');
With an appropriate import for the controller class.
as you primary key is not id so it will not work automatically you need to tell laravel to search by column name
code will be
Route::get('cp/site/{website:site_id}/modules/feeds', 'App\Http\Controllers\Modules_sites\Feeds\FeedController#index')->name('module_site.feeds.index');
you need to use {website:site_id}
ref link https://laravel.com/docs/8.x/routing#customizing-the-default-key-name
i will call a Controller all times. It is my GlobalController. I will use the Auth, and DB Function.
I doing this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use DB;
class GlobalController extends Controller
{
function user_in_party() {
// Get the logged user
$user = Auth::user();
print_R($user);
exit;
}
}
Now i call this from my Web.php (Routes) like this but i don't become the Authed user back why?
app('App\Http\Controllers\GlobalController')->user_in_party();
Can u help me? Or say me a better Solution?
Why are you using this Instead you can just Call
Auth::user();
its all global once a user is logged in you can get its details via Auth
I'm using Laravel and trying to do an SQL query from my Controller in a public function, but I'm really confused where I would put my table in the argument and if quotes go around the argument. Here is my code
public function selectMethod(){
$results = DB::select('select firstname from people where id = 1');
print_r($results);
return view('pages.selectMethod');
}
table is called people
My .env is configured to my database correctly and I get this error
FatalErrorException in AboutController.php line 90:
Class 'App\Http\Controllers\DB' not found
Thanks !
you should add use Illuminate\Support\Facades\DB;
at the top of your page
for example :
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* #return Response
*/
public function index()
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
Your error clearly states: Class 'App\Http\Controllers\DB' not found
Hence just use DB in your class. Add:
use DB;
At the top of the file just below the namespace line.
Also, I would suggest you to use Eloquent for your queries. It will make your life a lot easier and your code a lot beautiful.
Can you help me with this? I am currently studying Laravel on my own and I followed the tutorials in the Laracasts and it is awesome. Before Laravel I am using CodeIgniter and Opencart in my projects and I started to study Laravel because I want to learn a new framework.
In CI and Opencart all your database queries are in the model. But in Laravel you can perform and queries in Controller?. Is it a proper way to the queries in Laravel?
I have this kind of code in the Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller {
public function index() {
$articles = Article::all();
return view('articles.index')->with('articles', $articles);
}
}
Yes, this is perfectly fine for small applications.
For large-scale apps however, i'd recommend using repositories as they decouple your models from the controller - which makes them more readable and testable.
Your ArticlesController would translate to something like this:
<?php namespace App\Http\Controllers;
use App\Repositories\Articles\ArticleRepositoryInterface;
class ArticlesController extends Controller {
private $articles;
public function __construct(ArticleRepositoryInterface $articles)
{
$this->articles = $articles;
}
public function index()
{
return view('articles.index')
->with('articles', $this->articles->all());
}
}
Have a look at Laravels Service Container to understand the automatic resolution of the ArticleRepositoryInterface. Laracasts has some good videos on repositories.
Repositories is a smart decision to you. But why?
Basically, repositories is a 'gateway' between your application and your storage.
With repositories, you'll find your 'database queries' in a single place.
Let's think about the model Articles.
Instead of use a static instance of Articles all the times that you need to use it (Articles::find(), Articles::all(), etc), just create a repository of Articles.
Inject this repo in your controller (e.g.), and use 'features' storaged in your ArticleRepository.
What do you mean?
Let's consider a repository of Articles. What I'll use many times in my app of Articles model? I need select all, select by id, insert, update, delete. Basically these 'stuffs'. So, if I have all this stuffs in a place?
class ArticleRepository {
public function all(){}
public function getById($id){}
public function insert($data){}
public function update($data){}
public function delete($id){}
}
Inject this ArticleRepository in your controller. To do this, read a about IoC Container here: http://laravel.com/docs/5.0/container
The construct in your controller will be like this:
public function __construct(ArticleRepository $articles)
{
$this->articles = $articles;
}
Once all, when you need get all Articles in your controller, just do:
public function index()
{
$articles = $this->articles->all();
return View::make('articles.index')->with(['articles' => $articles]);
}
With this practice, you have a clean application with testables controllers and a beautiful organization and design. ;)
Look, I tried to be as didactic as possible to you understand the concept. The use of repositories is not only a way to do. So I let the links in the comments. And let other references here as well.
I'm sure you will understand quickly.
Success in learning! :)
https://laracasts.com/search?q=repositories&q-where=lessons
http://ryantablada.com/post/the-repository-pattern-in-action
http://culttt.com/2014/03/17/eloquent-tricks-better-repositories/
http://culttt.com/2013/07/15/how-to-structure-testable-controllers-in-laravel-4/
First
I wrote a migration script.
Second
I run the php artisan migrate to migrate the table into my database.
Database
Now, I have a subscribes table in my database.
It has 2 fields : id, and email.
Route
Route::post('/subscribe', array('as' =>'subscribe','uses'=>'AccountController#postSubscribe'));
Model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class Subscribe extends Model {
protected $table = 'subscribes';
//Validation Rules and Validator Function
public static function validator($input){
$rules = array(
'email' =>'required|email'
);
return Validator::make($input,$rules);
}
}
Controller
<?php namespace App\Http\Controllers;
use Input, Validator, Auth, Redirect;
class AccountController extends Controller {
public function postSubscribe() {
$subscribe = new Subscribe; <-------- Line#46 (BUG HERE)
$subscribe->email = Input::get('email');
$subscribe->save();
dd("Hi");
return Redirect::to('/')
->with('success','You have been successfully subscribe to us.');
}
}
?>
Error
Questions
Why can't I do $subscribe = new Subscribe;?
What is the best practice to insert data into database using Laravel 5 ?
Update
Thanks to #Mark Baker.
It seems that I have an issue with my namespace.
This namspacing is a bit confusing to me right now.
Can someone please clarify or explain that a bit ?
Anything is appreciated.
Thanks in advance.
Here is a high level overview of how namespaces work in PHP to try and help you understand this and give you a solution to your problem.
<?php
// This is the namespace of this file, as Laravel 5 uses PSR-4 and the
// App namespace is mapped to the folder 'app' the folder structure is
// app/Http/Controllers
namespace App\Http\Controllers;
// Use statements. You can include classes you wish to use without having
// to reference them by namespace when you use them further on in this
// namespaces scope.
use App\Subscribe;
class MyController extends BaseController
{
public function postSubscribe()
{
// You can now use the Subscribe model without its namespace
// as you referenced it by its namespace in a use statement.
$subscribe = new Subscribe();
// If you want to use a class that is not referenced in a use
// statement then you must reference it by its full namespace.
$otherModel = new \App\Models\Other\Namespace\OtherModel();
// Note the prefixed \ to App. This denotes that PHP should get this
// class from the root namespace. If you leave this off, you will
// reference a namespace relative to the current namespace.
}
}
You can try this, Simply use it :
$subscribe = new App\Subscribe;
Use App\Subscribe;.
Then you can use $subscribe = new Subscribe; in your code.